Abstract class with several levels.

I wrote the following code.

#include <iostream> using namespace std; class CI { public: virtual void display() =0; }; class Inter: public CI { public: int parseData (int); }; Inter::parseData (int data) { cout <<"Parsing the data "<<data; return data*100; } class Last: public Inter { public: void display(); }; void Last::display() { cout <<" Last:: Displaying From Last "<<endl; } class USB: public Inter { public: void display(); }; void USB::display() { cout <<" USB:: Displaying From Last "<<endl; } int main ( int argc, char ** argv) { int temp; CI *obj = new Last; obj->display(); temp = obj->parseData (100); cout <<"Parsed DAta .. "<<temp<<endl; delete obj; obj = new USB; obj->display(); temp = obj->parseData (200); } 

My question is:

Why can't I call the obj-> parseData function ?. In my understanding, Therefore, the class "Last" and "USB" comes from the class "Inter", should it be right to be called? ..

Tell me, where is my understanding wrong?

+4
source share
2 answers

obj must be declared as Last * or not less than Inter *

 Inter *obj = new Last; 

or

 Last *obj = new Last; 

If obj is just CI * , the compiler cannot see the parseData() method (your object is created as Last, but is immediately implicitly converted to CI and loses the advantage of the method).

I suggest you understand what upcast means. (See Also implicit conversion here or else) ...

+4
source

The parseData() method is not in the CI . Even if parseData() is made virtual , it still cannot be found. Remember that virtual functions will only cancel the behavior from the base class, but such a function can be called only through pointers to classes that already have such functions. First class in your hierarchy with parseData() in its Inter interface.

So, to solve this problem, you can define obj as Inter* , or you can also send it to Inter* on parseData call parseData . First preferred

 int main ( int argc, char ** argv) { int temp; Inter *obj = new Last; obj->display(); temp = obj->parseData (100); cout <<"Parsed DAta .. "<<temp<<endl; delete obj; obj = new USB; obj->display(); temp = obj->parseData (200); } 

Living example .

+1
source

Source: https://habr.com/ru/post/1485955/


All Articles