Sub topic 1
Base and Derived Classes
A class is a blueprint for objects. An object is a value made from a class. With inheritance, a derived class builds on a base class. The derived class can add or change behavior.
Here, Dog derives from Animal. Save the example as animals.cpp.
#include <iostream>
#include <string>
class Animal {
private:
std::string name_;
protected:
const std::string& name() const { return name_; }
public:
Animal(const std::string& name) : name_(name) {
std::cout << "Animal constructed\n";
}
virtual void speak() const {
std::cout << name_ << ": animal sound\n";
}
virtual ~Animal() {
std::cout << "Animal destroyed\n";
}
};
class Dog : public Animal {
public:
Dog() : Animal("Rex") {
std::cout << "Dog constructed\n";
}
void speak() const override {
std::cout << name() << ": woof\n";
}
~Dog() override {
std::cout << "Dog destroyed\n";
}
};
int main() {
Dog dog;
const Animal& animal = dog;
animal.speak();
}To compile and run it with a C++ compiler named g++:
g++ -std=c++17 animals.cpp -o animals
./animalsAccess to Inherited Members
A member is a value or function belonging to a class. public members are available to outside code. protected members are available inside the class and its derived classes. private members are available only inside their own class.
Dog can call the protected name() function, but it cannot use the private name_ directly. With public inheritance, public and protected base members keep those access levels.
Object Construction and Destruction Order
A constructor sets up an object; a destructor runs when its lifetime ends. The Animal part is constructed before the Dog part. Destruction happens in reverse: Dog first, then Animal. The program prints messages in that order.
Public Inheritance and Substitutability
Substitutability means a derived object can be used where its base is expected, while keeping the base’s promises. Use public inheritance when that relationship makes sense: a dog is an animal.
A reference is another name for an existing object. animal is an Animal reference to the dog object; it does not make a copy.
Virtual Functions and Runtime Dispatch
A virtual function lets a derived class supply its own version, called an override. override asks the compiler to check that the function matches a base virtual function.
Runtime dispatch selects the version for the actual object when the call runs. So animal.speak() prints Rex: woof, even though animal is an Animal reference. The virtual destructor also supports safe cleanup through a base pointer.
Exercise
Which constructor runs first, and which speak function does animal.speak() call?
Show answer
The Animal constructor runs first. The call uses Dog::speak(), because the actual object is a Dog.