Reputation:
How can i get my Base pointer to instantiate a derived object and use its functions? Is there a way to type cast this like java? Consider this sample code:
int main(){
cBase *pBase = 0;
if (1 < 2)
{
pBase = new cDerived;
}
}
class cBase
{public:
virtual void printMe()
{
std::cout << "printed cBase" << endl;
}
};
class cDerived: public cBase
{public:
virtual void printMe()
{
std:: cout << "printed cDerived" << endl;
}
};
However when i do this; it gives me an error "Expression must have class type".
cBase *pBase = 0;
if (1 < 2)
{
pBase = new cDerived;
pBase.printMe();
}
Upvotes: 1
Views: 187
Reputation: 21609
Fix it like this
#include <iostream>
using namespace std;
class cBase
{
public:
virtual ~cBase() {};
virtual void printMe()
{
std::cout << "printed cBase" << endl;
}
};
class cDerived: public cBase
{public:
virtual void printMe()
{
std:: cout << "printed cDerived" << endl;
}
};
int main(){
cBase *pBase = 0;
if (1 < 2)
{
pBase = new cDerived;
pBase->printMe();
delete pBase;
}
}
Steps to fix.
Move main
function after declaration of cBase
and cDerived
classes or forward declare those classes before main
.
Change pBase.printMe()
to pBase->printMe()
. Since pBase
is a pointer you must dereference it before accessing its members. pBase->printMe()
is like shorthand for (*pBase).printMe()
Plus a few other bits of housekeeping. Delete the pBase
object and since you are deleting a derived class (cDerived
) using a pointer to a base class (cBase
) you must declare the base classes destructor virtual, or the cBase
destructor will be called when pBase
is deleted when you really wanted the cDerived
destructor to be called here.
Upvotes: 1
Reputation: 445
In C++, in order to get to the method/field of a pointer to a class/structure, you have to use the -> operator.
Upvotes: 0