-3
class parent
{
  public:
    virtual void print()
    {
      printf("STUFF");
    }
};

class child : public parent
{
   public:
     virtual void print()
     {
        printf("other stuff");
     }
 };

 int main()
 {
    parent par = new child;
    par.print();
  }

When ever I try this, it always uses the parent function instead of the child function. I was trying to get it to use the child function instead.

deW1
  • 5,562
  • 10
  • 38
  • 54
icodenosleep
  • 49
  • 1
  • 5
  • 1
    because par is a parent type variable, your child will immediately casted to parent. If you want to call the child's function, use a pointer or reference to base class, like: `parent& par = new child ();` – Melkon Sep 11 '14 at 12:20
  • 9
    `parent par = new child;` this line shouldn't compile – Jaffa Sep 11 '14 at 12:20
  • If your real code is something like `parent par = *(new child);`, then that's because you're copying the parent part of the object and discarding (and leaking) the `child` object you copied it from. If it's actually `parent * par = ...` and `parent->print()`, then you should see the child's override. Without seeing the code that you're actually compiling, we can't guess what's wrong with it. – Mike Seymour Sep 11 '14 at 12:23
  • 5
    By the way, this is *overriding*, not *overloading*. Overloading is when two functions *in the same scope* have the same name, but differ in some way. Overriding is when a derived class redefines a parent's virtual function. – Mike Seymour Sep 11 '14 at 12:25
  • when you use the new operator use the delete operator as well please. – deW1 Sep 11 '14 at 12:35
  • 1
    The code doesn't compile. Please present the code that gives the error described in the question. – Galik Sep 11 '14 at 12:37

1 Answers1

0
class parent
{
public:
    virtual void print()
    {
        printf("STUFF");
    }
};

class child : public parent
{
public:
    virtual void print()
    {
        printf("other stuff");
    }
};

int main()
{
    parent *par = new child;
    par->print();
    delete par;
    par = NULL;
}
wshcdr
  • 935
  • 2
  • 12
  • 27