954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

virtual methods and inheritance

I'm trying to create a Mammal class which has two virtual methods, and one non virtual methods to demonstrate inheritance. I've written the class, but now I have a few errors, and a few questions. First of all, I'm recieving an error that says the following methods aren't declared:
speak();
move();
printName();

It works fine if I declare a Dog class(derived) and then use the dot operator to call these methods, but when I try to create a Pointer to a base class which is assigned to a derived class, then I get the errors:
Mammal* ptr = new Dog;

Here's the code:

#include <cstdlib>
#include <iostream>

//using namespace std;

class Mammal
{
      public:
             Mammal();
             ~Mammal();
             virtual void speak() { std::cout << "Mammal Speaking..."; }
             virtual void move() { std::cout << "Mammal moving..."; }
             void printName() { std::cout << "Mammal..."; }
      private:
};

/**
 *Mammal
 */
Mammal::Mammal()
{
}
Mammal::~Mammal()
{
}

/**
 *Dog
 */
class Dog : public Mammal
{
      public:
             Dog();
             ~Dog();
             virtual void speak();
             virtual void move();
             void printName();
      private:
};

Dog::Dog()
{
}
Dog::~Dog()
{
}
void Dog::speak()
{
     std::cout << "Bark. Bark...." << std::endl;
}
void Dog::move()
{
    std::cout << "Dog moving..." << std::endl;
}
void Dog::printName()
{
     std::cout << "Dog...." << std::endl;
}

/**
 *Main
 */
int main()
{

    std::cout << std::endl << std::endl << "Creation of Mammal Pointer" << std::endl;
    Mammal* ptr = new Dog;
    <strong>ptr.speak();</strong>
    <strong>ptr.move();</strong>
    <strong>ptr.printName();</strong>
    
    int x;
    std::cin >> x;
    
    return 0;
}


Now I have a one more question. How come I can't declare a dog object like this:
Mammal m = new Dog;

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

ptr.speak();
ptr.move();
ptr.printName();

not . its ->

Stoned_coder
Junior Poster
164 posts since Jul 2005
Reputation Points: 19
Solved Threads: 5
 
Now I have a one more question. How come I can't declare a dog object like this: Mammal m = new Dog;

because 'operator new' returns a pointer to a 'Dog' instance (a Dog*), and m is not a Dog*.

polymorphism works in c++ only when dealing with pointers. You can make your dog speak (sure you can !) by doing :

Mammal *m=new Dog;
m->speak();
CrazyDieter
Junior Poster
108 posts since Jul 2005
Reputation Points: 11
Solved Threads: 6
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You