Inheritance

Base class

class A 
{
    public:
       int x;
    protected:
       int y;
    private:
       int z;
};
  • ์œ„์™€ ๊ฐ™์€ Base class๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ณ , ๊ฐ ์ผ€์ด์Šค๋ฅผ ์‚ดํŽด๋ณธ๋‹ค

public inheritance

class B : public A
{
    void func_b()
    {
        x = 10;     // x is public
        y = 15;     // y is protected
        // z = 20;  // z is private, not accessible
    }
};

// ...

int main()
{
    B b;

    b.x = 10;     // x is public
    // b.y = 15;  y is protected, not accessible
    // b.z = 20;  z is private,   not accessible
}
  • ์ผ๋ฐ˜์ ์œผ๋กœ ๊ฐ€์žฅ ๋งŽ์ด ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ์‹
  • Base class์˜ public ๋ณ€์ˆ˜์— ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค
  • Base class์˜ protected ๋ณ€์ˆ˜์—๋„ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค
  • Base class์˜ private ๋ณ€์ˆ˜์—๋Š” ์ ‘๊ทผ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค

protected inheritance

class C : protected A
{
    void func_c()
    {
        x = 10;     // x is protected
        y = 15;     // y is protected
        // z = 20;  // z is private,  not accessible
    }
};

// ...

int main()
{
    C c;

    // c.x = 10; x is protected,  not accessible
    // c.y = 15; y is protected,  not accessible
    // c.z = 20; z is private,    not accessible
}
  • public ํ‚ค์›Œ๋“œ๊ฐ€ ๋ถ™์–ด์žˆ๋˜ x ๋ณ€์ˆ˜๊ฐ€ protected๊ฐ€ ๋œ๋‹ค
  • y์™€ z๋Š” ๊ธฐ์กด์˜ ํ‚ค์›Œ๋“œ๋ฅผ ์œ ์ง€ํ•œ๋‹ค
  • ํ•˜์œ„ ํด๋ž˜์Šค์—์„œ์˜ ์ ‘๊ทผ ์—ฌ๋ถ€๋Š”?
    • ์œ ์ง€๋œ๋‹ค

private inheritance

class D : private A    // 'private' is default for classes
{
    void func_d()
    {
        x = 10;     // x is private
        y = 15;     // y is private
        // z = 20;  // z is private, not accessible
    }
};

// ...

int main()
{
    D d;

    // d.x = 10; x is private, not accessible
    // d.y = 15; y is private, not accessible
    // d.z = 20; z is private, not accessible
}
  • ์ƒ์† ํ‚ค์›Œ๋“œ๋ฅผ ๋ช…์‹œํ•˜์ง€ ์•Š๋Š” ๊ฒฝ์šฐ์˜ default
  • public ํ‚ค์›Œ๋“œ์˜ x์™€ protected ํ‚ค์›Œ๋“œ๊ฐ€ ๋ถ™์€ y๊ฐ€ private์ด ๋œ๋‹ค
  • z๋Š” ๊ธฐ์กด์˜ ํ‚ค์›Œ๋“œ๋ฅผ ์œ ์ง€ํ•œ๋‹ค
  • ํ•˜์œ„ ํด๋ž˜์Šค์—์„œ์˜ ์ ‘๊ทผ ์—ฌ๋ถ€๋Š”?
    • ์—ญ์‹œ ์œ ์ง€๋œ๋‹ค

๊ฒฐ๋ก 

post_thumbnail

  • ์™ธ๋ถ€์—์„œ ์ ‘๊ทผ ์‹œ public -> protected -> private ์ˆœ์„œ๋กœ ์ ‘๊ทผ ์ œ์–ด์ž๊ฐ€ ์ œํ•œ๋œ๋‹ค
  • ๊ทธ๋Ÿฌ๋‚˜ ๋‚ด๋ถ€์—์„œ์˜ ์ ‘๊ทผ์€ ์œ ์ง€๋œ๋‹ค

์ถœ์ฒ˜

Categories: ,

Updated: