1

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();
    }
4
  • 1
    Where is your definition of cBase? Commented Feb 19, 2015 at 23:36
  • does it need one? i just made this example up Commented Feb 19, 2015 at 23:39
  • 1
    pBase.printMe(); ===> pBase->printMe();, and printMe() had better be a member (virtual or otherwise) of cBase. Commented Feb 19, 2015 at 23:43
  • It needs it to be working code. Do you have a definition of cBase with a virtual function printMe? Commented Feb 19, 2015 at 23:46

2 Answers 2

1

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.

  1. Move main function after declaration of cBase and cDerived classes or forward declare those classes before main.

  2. 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.

Sign up to request clarification or add additional context in comments.

Comments

0

In C++, in order to get to the method/field of a pointer to a class/structure, you have to use the -> operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.