Yes, this is definitely possible. In fact, this is a classic example of polymorphism in object-oriented programming.
In your example code, you have correctly defined the parent class as abstract by defining the method A() as an empty method to be overridden by the child classes. This means that any instance of the parent class cannot be created, but only instances of the child classes that have implemented the method A().
The method B() in the parent class can contain the common code that you want to reuse across all child classes, and it can call the method A(), which will be overridden in each child class to perform the specific implementation of that method for that child class.
Here's your example code with some minor corrections to the syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
class Parent {
public:
virtual void A() = 0; // empty method to be overridden by child classes
void B() {
// code block that stays the same for all child classes
A();
// code block that stays the same for all child classes
}
};
class Child : public Parent {
public:
void A() override {
// code of the method specific to this child class
}
};
int main() {
Child testObject;
testObject.B(); // calls the common code in Parent.B() and the implementation of Child.A()
return 0;
}
|
In this example, the Parent class is defined as abstract by making method A() a pure virtual function (using = 0), and the Child class inherits from Parent and overrides the A() method with its own implementation. The main() function creates an instance of the Child class and calls its B() method, which in turn calls the implementation of A() in the Child class.