[C++] Object-Oriented Programming: Inheritance (ENG)
Difference between Java and C++
// Java
public class Cat extends Animal
{
private String Name;
public Cat(int age, String name)
{
super(age); // calls Animal(int age)
Name = name;
}
}
// C++
class Cat : public Animal
{
public:
Cat(int age, const char* name);
private:
char* mName;
};
Cat::Cat(int age, const char* name)
: Animal(age)
{
size_t size = string(name) +1;
mName = new char[size];
strcpy(mName, name);
}
Access Modifier
When the class is inherited, the child class can change access to the members of the parent class. It follows a more strict modifier among the existing access modifier of the parent class and the inheritance access modifier.
- public inheritance
- private inheritance
- protected inheritance
Memory Structure
Animal * a = new Cat( ...... );
|
This is okay cause,
// Animal.cpp
Animal::Animal(int age)
: mAge(age)
{
}
// Cat.cpp
Cat::Cat(int age, const string& name)
: Animal(age)
{
size_t size = strlen(name) + 1;
mName = new char[size];
strcpy(mName, name);
}
// main.cpp
Cat* myCat = new Cat(2, "Mew")
these codes allocate memory like below. Cat knows the memory layout of Animal. They always be allocated side by side (parent first).
Calling the Constructor
A constructor of the parent class is called first, and then a constructor of the child class is called. When you want to call specific constructor of the parent class, you have to use an initialization list.
Cat::Cat(int legs, int age, const string& callingName)
: Animal(legs, age) // Explicit call
, mCallingName(callingName)
{
}
case 1 the parent class with a constructor which has no parameter
// Animal.h
class Animal
{
public:
Animal();
private:
int mAge;
}
// Animal.cpp
Animal::Animal()
: mAge(0)
{
}
// Cat.cpp
Cat::Cat(int age, const string& name) // calls Animal() implicitly
{
size_t size = strlen(name) + 1;
mName = new char[size];
strcpy(mName, name);
}
// main.cpp
Cat* myCat = new Cat(2, "Mew");
case 2 the parent class without a constructor which has no parameter (Compile Error below)
// Animal.h
class Animal
{
public:
Animal(int age);
private:
int mAge;
};
// Animal.cpp
Animal::Animal(int age) // the only constructor which Animal has.
:mAge(age)
{
}
// Cat.cpp
Cat::Cat(int age, const string& name) // calls Animal() implicitly
{
size_t size = strlen(name) + 1;
mName = new char[size];
strcpy(mName, name);
}
// main.cpp
Cat* myCat = new Cat(2, "Mew");
Deleting the Child Object
// Super Simple Example
// Animal.cpp
Animal::~Animal()
{
}
// Cat.cpp
Cat::~Cat()
{
delete mName; // calls ~Animal()
}
// main.cpp
delete myNeighboursCat;
// ...
Order of calling the destructors contrays to the order of calling the constructors. At the end of the child class destructor, the destructor of the parent class is automatically called.