Junior — Middle
Is it possible to access methods defined in a parent class from an instance of its child class?
sobes.tech AI
Answer from AI
Yes, in C++, an instance of a derived class can access methods defined in its parent class if those methods are accessible (for example, if they have the access modifier public or protected). This is one of the main features of inheritance — the derived class inherits the behavior of the parent and can use its methods directly.
Example:
class Parent {
public:
void greet() {
std::cout << "Hello from Parent" << std::endl;
}
};
class Child : public Parent {
public:
void greetChild() {
greet(); // call to parent method
std::cout << "Hello from Child" << std::endl;
}
};
int main() {
Child c;
c.greetChild();
return 0;
}