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

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

by 2den 2022. 1. 2.
728x90

 

Memory of the Member Function

Member functions are allocated to the memory only once while compliling.

 

 

 

Function Overriding

// Animal.h
class Animal
{
public:
    void Speak();
}

// Animal.cpp
void Animal::Speak()
{
    std::cout << "An animal is speaking" << std::endl;
}
 
// Cat.h
class Cat : public Animal
{
public:
    void Speak();
}

// Cat.cpp
void Cat::Speak()
{
    std::cout << "Meow" << std::endl;
}
 
// Main.cpp
Cat* myCat = new Cat();
myCat->Speak();    // Meow

Animal* yourCat = new Cat();
yourCat->Speak();  // An animal is speaking
 

 

 

Static Binding

Cat* yourCat = new Cat(5, "Mocha");    // calls functions of Cat class
Animal* yourCat = new Cat(5, "Mocha"); // calls functions of Animal class
 

 

 

Dynamic Binding - Virtual Function

// Animal.h
class Animal
{
public:
    virtual void Move();
    virtual void Speak();
};

// Animal.cpp
void Animal::Move()
{
}
void Animal::Speak()
{
    std::cout << "An animal is speaking" << std::endl;
}
 
// Cat.h
class Cat : public Animal
{
public:
    void Speak();
}

// Cat.cpp
void Cat::Speak()
{
    std::cout << "Meow" << std::endl;
}
 
// Main.cpp
Cat* myCat = new Cat(2, "Coco");
myCat->Speak();    // Meow

Animal* yourCat = new Cat(5, "Mocha");
yourCat->Speak();  // Meow
 

Don't forget the virtual keyword.

 

If you use virtual functions, always the member functions of the child class are called. (Even if the pointer or reference of the parent class is being used.) Dynamic(late) binding is slower than static binding.

 

The virtual table is created for virtual binding. It contains addresses of the all virtual member functions. Virtual tables are created for each class, not for each object. Each object has an address of the virtual table.

 

 

 

Virtual Destructor

// Animal.h
class Animal
{
public:
    virtual ~Animal();
private:
    int mAge;
};
 
// Cat.h
class Cat : public Animal
{
public:
    // can omit but write
    virtual ~Cat();
private:
    char* mName;
};

// Cat.cpp
Cat::~Cat()
{
    delete mName;
}
 

 

 

728x90

댓글