Why do programmers use inheritance in C++?
Think about how you can build new things based on old things without rewriting everything.
Inheritance allows a new class to use properties and methods of an existing class, promoting code reuse and logical organization.
What is the output of this C++ code using inheritance?
#include <iostream> class Animal { public: void speak() { std::cout << "Animal speaks" << std::endl; } }; class Dog : public Animal { public: void speak() { std::cout << "Dog barks" << std::endl; } }; int main() { Dog d; d.speak(); return 0; }
Which speak() method is called when using a Dog object?
The Dog class overrides the speak() method, so calling speak() on a Dog object prints "Dog barks".
What error does this C++ code produce?
#include <iostream> class Base { public: void show() { std::cout << "Base" << std::endl; } }; class Derived : Base { }; int main() { Derived d; d.show(); return 0; }
Check the default inheritance access level in C++ classes.
In C++, class inheritance is private by default, so Base's public members become private in Derived, making show() inaccessible.
Which option shows the correct syntax for public inheritance in C++?
Remember the keyword used in C++ for inheritance.
C++ uses a colon and the keyword 'public' to specify public inheritance.
Given the following code, how many members are accessible directly from an object of class Derived?
class Base {
public:
int a;
protected:
int b;
private:
int c;
};
class Derived : public Base {
public:
void func() {
a = 1;
b = 2;
// c = 3; // Is this accessible?
}
};
int main() {
Derived d;
d.a = 5;
// d.b = 6; // Is this accessible?
// d.c = 7; // Is this accessible?
return 0;
}Consider the access levels and where they apply.
Public members are accessible from outside. Protected members are accessible inside Derived but not from outside objects. Private members are not accessible at all.