Adham Mamdouh
Adham Mamdouh

Reputation: 11

calling child class function

How can I call a child function from a pointer of type parent that points to the child?

class a{
public:
    virtual void print(){cout << "From a" << endl;}
};

class b: public a{
public:
    void print(){cout << "Form b" << endl;}
    void printFunction(){cout << "Exist in b" << endl;}
};

int main() {

    a* Obj = new b;

    Obj->print();
    Obj->printFunction();
    return 0;
}

Here I have a pointer of type "a" that points to "b". I want to call "printFunction" that's defined only in class b.

I got this error:

'class a' has no member named 'printFunction'

The question is how can I call "printFunction" using this pointer? or how To apply casting here?

Upvotes: 1

Views: 101

Answers (2)

andres
andres

Reputation: 321

You could downcast using dynamic_cast conversion

class base {
  public:
    void print() {std::cout << "base class print";}
};

class derived : public base {
  public: 
    void printFunction() {std::cout << "derived class print";}
};

int main() {

  base* ptr_derrived  = new derived();

  if(Derived* d = dynamic_cast<derived*>(ptr_derived) {
    std::cout << "downcast successful\n";
    d->printFunction(); // safe to call
  }

  delete ptr_derrived;

}

Upvotes: 0

pm100
pm100

Reputation: 50210

Use dynamic_cast:

class a{
public:
    virtual ~a(){}
    virtual void print(){ cout << "From a" << endl; }
};

class b: public a{
public:
    void print(){ cout << "Form b" << endl; }
    void printFunction(){ cout << "Exist in b" << endl; }
};

int main() {

    a* Obj = new b;

    Obj->print();

    b* bObj = dynamic_cast<b*>(a);
    if (bObj)
        bObj->printFunction();

    delete a;

    return 0;
}

Upvotes: 5

Related Questions