1

I've a question regarding inheritance I've found this tutorial online, and was wondering why the output for "Dog" is actually "Animal print" I understand that Animal pointer is pointing to the address of Dog, but why isn't it printing "Dog print"?

Kindly help me out, I'm new to C++.

Below is the code:

#include <iostream>
using namespace std;

class Animal { 
public:
   void print();
};
void Animal::print() {
    cout << "Animal print" << endl;
}

class Dog : public Animal {
public:
   void print();
};

void Dog::print() {
   cout << "Dog print" << endl;
}

int main() {

Dog h;
Animal *eptr = &h;

eptr->print();
eptr->Animal::print();

}

Output:

Animal print
Animal print
totoro
  • 11
  • 2
  • You forgot to write "virtual". If the tutorial doesn't mention it or explain its purpose, get a different tutorial. Or even better, [a book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Apr 08 '16 at 10:38
  • Try `virtual void Animal::print() ..` for expected result – hr_117 Apr 08 '16 at 10:38
  • Hi , the code that I found have no virtual in it. Could you help in explaining the code that I've posted? – totoro Apr 08 '16 at 10:43
  • 1
    @totoro did you at least try a look to the link HostileFork mentioned? – hr_117 Apr 08 '16 at 10:50

1 Answers1

1

Here the child class object (dog) is pointed by a base class object (animal). But its limitation is only up to base class behavior.

#include <iostream>
using namespace std;

class Animal { 
public:
   virtual void print();
};

 void Animal::print() {
    cout << "Animal print" << endl;
}

class Dog : public Animal {
public:
   void print();
};

void Dog::print() {
   cout << "Dog print" << endl;
}

int main() {

Dog h;
Animal *eptr = &h;

eptr->print();
eptr->Animal::print();

}

You can use virtual function in order to access child class through base class object.

Pavan
  • 250
  • 3
  • 13