C++: new base class,but it can access the derived class's property -


#include <iostream> using namespace std; class animal {    public:    void breathe()    {      cout << "breathe!" << endl;    }     int height; }; class fish : public animal {   public:    void breathe()    {      cout << "fish breathe!" << endl;    }    int weight; }; int main() {   animal *p_animal = new animal();   fish *p_fish = (fish *)p_animal;    p_fish->breathe();   p_fish->weight = 2;   cout << p_fish->weight; //i new animal instance,but why has weight property?    int temp;   cin >> temp; } 

some side comments on code.

in example, want virtual functions. see modification of code comments :

#include <iostream>  class animal {   public:     virtual ~animal() {} // define virtual destructor in case     virtual void breathe() const  // fonction doesn't modify object     {                             // then, add 'const' @ end       std::cout << "breathe!" << std::endl;     }     unsigned int height; // animal can't have negative height ;-)                          // then, use 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 () empty constructor   animal* p_fish = new fish;    p_animal->breathe(); // prints "breathe!"   p_fish->breathe();  // prints "fish breathe!" if pointer                       // pointer animal. it's behaviour of virtual                       // functions : when code executed, real type                       // checked , corresponding function called.    p_fish->height = 10;  // works   // p_fish->weight = 5;  // doesn't compile, it's pointer animal    fish* p_real_fish = dynamic_cast<fish*>(p_fish);   p_real_fish->height = 10;  // works   p_real_fish->weight = 5;  // works    delete p_animal;  // don't forget release memory !   delete p_fish; } 

i hope can you.


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -