Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assigning derived class pointer to base class pointer in C++

Tags:

c++

I have following

class base
{
};

class derived : public base
{
  public:
   derived() {}
   void myFunc() { cout << "My derived function" << std::endl; }

};

now I have

base* pbase = new derived();
  pbase->myFunc();

I am getting error myFunc is not a member function of base.

How to avoid this? and how to make myFunc get called?

Note I should have base class contain no function as it is part of design and above code is part of big function

like image 273
venkysmarty Avatar asked Nov 19 '12 09:11

venkysmarty


People also ask

Can a pointer of derived class point to base class?

Derived class pointer cannot point to base class.

Can we assign derived class object to base?

In C++, a derived class object can be assigned to a base class object, but the other way is not possible.

How do you call a derived class from base class?

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

What can hold the address of a pointer to the base class object or be derived class object Mcq?

Explanation: The syntax must contain * symbol after the className as the type of object. This declares an object pointer. This can store address of any object of the specified class. 3.


1 Answers

If you are adamant that this function should NOT be a part of base, you have but 2 options to do it.

Either use a pointer to derived class

derived* pDerived = new derived();
pDerived->myFunc();

Or (uglier & vehemently discouraged) static_cast the pointer up to derived class type and then call the function
NOTE: To be used with caution. Only use when you are SURE of the type of the pointer you are casting, i.e. you are sure that pbase is a derived or a type derived from derived. In this particular case its ok, but im guessing this is only an example of the actual code.

base* pbase = new derived();
static_cast<derived*>(pbase)->myFunc();
like image 112
Karthik T Avatar answered Sep 19 '22 12:09

Karthik T