Itay Avraham
Itay Avraham

Reputation: 393

Call derived class method from base class instance without casting

There is another way to call derived class method from a base pointer object without casting?

class Base
{
};

class Derived : public Base
{
    public:
    void set() {printf("bbbbbbbbbbbb"); }

};

int main()
{
  Base* pbBase;

  pbBase = new Derived();

  //pbBase->set(); // Compilation error.
  (Derived*)pbBase->set(); // Working.
}

Upvotes: 1

Views: 326

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

You can add virtual methods in Base that you override in Derived.

Note that you should make the destructor virtual too or else the derived class' destructor would not get called when you delete the object through a base class pointer.

#include <iostream>

class Base
{
public:
    virtual ~Base() = default;
    virtual void set() = 0;    // = 0 makes it pure virtual
};

class Derived : public Base
{
public:
    void set() override { std::cout << "bbbbbbbbbbbb\n"; }

};

int main()
{
  Base* pbBase;

  pbBase = new Derived();

  pbBase->set();

  delete pbBase;
}

Upvotes: 5

Related Questions