0

I am trying to call a function in a derived class with the same name existing in the base class. The function simply prints class elements. For example:

class A                             // Base Class
{                                    
public:                          
     string a;
     int b;

     A(){};                         //Default Constructor                         
     A(string x,int y):a(x),b(y){}  //Parametrized Constructor
     ~A(){};                        //Destructor
     void printInfo()
     {
        cout << a << endl;
        cout << b << endl;
     };     
};

class B:public A                    // Derived Class
{                                    
public:                          
     string c;


     B(){};                         //Default Constructor                         
     B(string z):c(z){}             //Parametrized Constructor
     ~B(){};                        //Destructor
     void printInfo()
     {
        cout << a << endl;
        //I am trying to call printInfo of A inside this function
     }; 
};

So that in the output, when I create an object of B (let's say B example;) and try to use printInfo() member function of class B (Ex: example.printInfo();), I would print first c and then a and b. Also it will not be limited with 2 classes, but more than 5 classes having a common printInfo() member function. How do I achieve this ?

Alex
  • 5
  • 2
  • Your `printInfo` will need a return type. Then you just do `A::printInfo()`… – Michael Kenzel Nov 27 '19 at 00:21
  • @MichaelKenzel Sorry not to mention the type of my member function. It is a ```void``` function, so it doesn't return anything. I uptaded the code. – Alex Nov 27 '19 at 00:24

1 Answers1

0

//I am trying to call printInfo of A inside this function

class B:public A                    // Derived Class
{                                    
public:                          
     string c;


     B(){};                         //Default Constructor                         
     B(string z):c(z){}             //Parametrized Constructor
     ~B(){};                        //Destructor
     printInfo()
     {
        cout << a << endl;
        A::printInfo();  //<-- call base class version
     }; 
};
artm
  • 17,291
  • 6
  • 38
  • 54