[Solved] C++: new base class,but it can access the derived class’s property

[ad_1]

Some side comments on your code.

In this example, you probably want virtual functions. See this modification of your code with some comments :

#include <iostream>

class Animal
{
  public:
    virtual ~Animal() {} // Always define virtual destructor in this case
    virtual void breathe() const  // This fonction doesn't modify the object
    {                             // then, add 'const' at the end
      std::cout << "breathe!" << std::endl;
    }
    unsigned int height; // An animal can't have a negative height ;-)
                         // then, use an unsigned type.
};

class Fish : public Animal
{
  public:
    virtual ~Fish() {}
    virtual void breathe() const
    {
      std::cout << "fish breathe!" << std::endl;
    }
    unsigned int weight;
};

int main()
{
  Animal* p_animal = new Animal;  // Don't put () for empty constructor
  Animal* p_fish = new Fish;

  p_animal->breathe(); // this prints "breathe!"
  p_fish->breathe();  // this prints "fish breathe!" even if the pointer is
                      // an pointer to Animal. It's the behaviour of virtual
                      // functions : when the code is executed, the real type
                      // is checked and the corresponding function is called.

  p_fish->height = 10;  // This works
  // p_fish->weight = 5;  // This doesn't compile, it's an pointer to Animal

  Fish* p_real_fish = dynamic_cast<Fish*>(p_fish);
  p_real_fish->height = 10;  // This works
  p_real_fish->weight = 5;  // This works too

  delete p_animal;  // Don't forget to release the memory !
  delete p_fish;
}

I hope this can help you.

[ad_2]

solved C++: new base class,but it can access the derived class’s property