cpp_상속 - 8BitsCoding/RobotMentor GitHub Wiki

cpp_inheritance

// Animal.h
class Animal {
public:
    Animal(int age);
private:
    int mAge;
};

// Cat.h
class Cat : public Animal {
public:
    Cat(int age, const char* name);
private:
    char* mName;
};

// Cat.cpp
Cat::Cat(int age, const char* name) : Animal(age) {
    size_t sie = strlen(name) + 1;
    strcpy(mName, name);
}

상속시 주의 사항

다음과 같은 구현을 통해 특정 클래스에서만 사용할 수 있는 함수를 구현 가능 일종의 인터페이스 패턴

class bird {
    
};

class flyablebird : public bird {
public:
    void fly();
};

class penguin : public bird {};

penguin p;
p.fly();
// Compile Error

아래의 결과를 예측해보자.

class dog {
public:
    void bark() { cout << "dog, I am" << endl; }
};

class yellowdog : public dog {
public:
    void bark() { cout << "yellowdog, I am" << endl; }
};

int main() {
    yellowdog* py = new yellowdog();
    py->bark();
    dog* pd = py;
    pd->bark();
}

yellowdog, I am

dog, I am

dog, I am결과도 컴파일러에 따라서 다르게 나올 수 있다.

이 문제를 어떻게 해결하나?

virtual 이용

class dog {
public:
    void bark(int age) { cout << " I am " << age << " years old" << endl;}
    virtual void bark(string msg = "just a") { cout << "Whoof, I am" << msg << " dog." << endl; }
};

class yellowdog : public dog {
public:
    virtual void bark(string msg = "a yellow") { cout << "Whoof, I am" << msg << " dog." << endl; }
};

int main() {
    yellowdog* py = new yellowdog();
    py->bark(5);
    // Compile Error
}

또 다른 문제

다음과 같이 해결가능 void bark(int age)는 어떻게 호출하나?

class dog {
public:
    void bark(int age) { cout << " I am " << age << " years old" << endl;}
    virtual void bark(string msg = "just a") { cout << "Whoof, I am" << msg << " dog." << endl; }
};

class yellowdog : public dog {
public:
    using dog::bark();
    virtual void bark(string msg = "a yellow") { cout << "Whoof, I am" << msg << " dog." << endl; }
};

int main() {
    yellowdog* py = new yellowdog();
    py->bark(5);
}