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;
    [b]ptr.speak();[/b]
    [b]ptr.move();[/b]
    [b]ptr.printName();[/b]
    
    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;

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

not . its ->

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();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.