C ++ link return in const member function

A have a class hierarchy that looks something like this:

class AbstractDataType { 
public: 
   virtual int getInfo() = 0;
}; 

class DataType: public AbstractDataType { 
public:
   virtual int getInfo() { }; 
};

class Accessor { 
    DataType data; 
public: 
    const AbstractDataType& getData() const { 
        return(data); 
    } 
};

Well, GCC 4.4 reports:

In the member function 'const AbstractDataType & Accessor :: getData () const: error: incorrect initialization of a link of type' const AbstractDataType & from an expression of type 'const DataType

Where am I mistaken - is this the case when I SHOULD use a pointer?

[edit - fixed half columns]

+3
source share
2 answers

No, you do not need to use a pointer. In this case, you can use a link or a pointer.

, , g ​​++ 4.4 Visual Studio 2010.... .

, , .

, ?

class DataType /*: public AbstractDataType*/ { 
public:
   virtual int getInfo() { }; 
};
+4

GCC , . DataType, . :

return data;
0

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


All Articles