Introduction
Method overriding lets a child class change how a method works from its parent class. This helps customize behavior without changing the original code.
class Parent { public: virtual void methodName() { // parent method code } }; class Child : public Parent { public: void methodName() override { // child method code } };
class Animal { public: virtual void sound() { std::cout << "Some sound" << std::endl; } }; class Dog : public Animal { public: void sound() override { std::cout << "Bark" << std::endl; } };
class Vehicle { public: virtual void start() { std::cout << "Vehicle starting" << std::endl; } }; class Car : public Vehicle { public: void start() override { std::cout << "Car starting" << std::endl; } };
#include <iostream> class Parent { public: virtual void greet() { std::cout << "Hello from Parent" << std::endl; } }; class Child : public Parent { public: void greet() override { std::cout << "Hello from Child" << std::endl; } }; int main() { Parent* p = new Parent(); Parent* c = new Child(); p->greet(); // Calls Parent greet c->greet(); // Calls Child greet because of overriding delete p; delete c; return 0; }
method overriding in C++?virtual to allow overriding.virtual void display();. void display() override; uses override incorrectly in declaration, it is used in child method definition. Options C and D have wrong syntax.class Base {
public:
virtual void show() { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
void show() override { std::cout << "Derived" << std::endl; }
};
int main() {
Base* ptr = new Derived();
ptr->show();
delete ptr;
return 0;
}show() is virtual, the Derived version is called.class Parent {
public:
void greet() { std::cout << "Hello from Parent" << std::endl; }
};
class Child : public Parent {
public:
void greet() override { std::cout << "Hello from Child" << std::endl; }
};virtual. Here, it is not.override, which requires the parent method to be virtual. Since parent method is not virtual, this causes a compilation error.ptr->display(); is called?class Animal {
public:
virtual void display() { std::cout << "Animal" << std::endl; }
};
class Dog : public Animal {
public:
void display() override { std::cout << "Dog" << std::endl; }
};
class Puppy : public Dog {
public:
void display() override { std::cout << "Puppy" << std::endl; }
};
int main() {
Animal* ptr = new Puppy();
ptr->display();
delete ptr;
return 0;
}display() with its own version. The pointer is of type Animal* but points to a Puppy object.display() is virtual, the most derived override (Puppy::display) is called at runtime.Pass the test and this pattern moves unknown