본문 바로가기
College Study/C++ (ENG)

[C++] Object-Oriented Programming: Interface (ENG)

by 2den 2022. 1. 2.
728x90

 

 

Multiple Inheritance

// Faculty.h
class Faculty
{
};

// Student.h
class Student
{
};

// TA.h
class TA : public Student, public Faculty
{
};

// Main.cpp
TA* myTA = new TA();
 

The constructors are called in the order of the parent class in the child class declaration. (Regardless of the order of the initialiation list.)

 

problem 1: Compiler doesn't know which function is supposed to be called.

// Main.cpp
TA* myTA = new TA();
myTA->DisplayData();  // ?
 

You have to specify the function is from which parent class.

myTA->Student::DisplayData();
 

 

problem 2: Diamond Problem

Use virtual parent class.

// Animal.h
class Animal
{
};

// Tiger.h
class Tiger : virtual public Animal
{
};

// Lion.h
class Lion : virtual public Animal
{
};

// Liger.h
class Liger : public Tiger, public Lion  // doesn't have duplicate memory of Animal
{
};
 

 

Do not use multiple inheritance as much as possible. Use the interface instead.

 

 

 

Abstract Class

Pure virtual function has no implementation. So the child class of it has to implement the function.

// Animal.h
class Animal
{
public:
    virtual void Speak() = 0;  // pure virtual function
private:
    int mAge;
};
 
// Cat.h
class Cat : public Animal
{
public:
    Cat(int age, const char* name);
    // void Speak();
private:
    char* name;
};

// compile error
// Speak() is not implemented
 

Parent class that has a pure virtual function is an abstract class. An abstract class can't create an object. But can be used for a pointer or reference.

// Animal.h
class Animal
{
public:
    virtual void Speak() = 0;  // pure virtual function
private:
    int mAge;
};
 
Animal myAnimal;                  // compile error

Animal* myAnimal = new Animal();  // compile error

Animal* myCat = new Cat();        // okay

Animal& myCatRef = *myCat;        // okay
 

 

 

Interface

// IFlyable.h
class IFlyable
{
public:
    virtual void Fly() = 0;
};
 
// IWalkable.h
class IWalkable
{
public:
    virtual void Walk() = 0;
}
 
// Bat.h
class Bat : public IFlyable, public IWalkable
{
public:
    void Fly();
    void Walk();
};
 
// Cat.h
class Cat : public IWalkable
{
public:
    void Walk();
};
 

Interface doesn't have any member function. (If you need, it's okay.)

 

728x90

댓글