views:

127

answers:

2

A have a class hierarchy that looks somethign 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 member function ‘const AbstractDataType& Accessor::getData() const’: error: invalid initialization of reference of type ‘const AbstractDataType&’ from expression of type ‘const DataType’

Where am I going wrong - is this a case where I MUST use a pointer?

[edit - fixed semi-colons]

A: 

I don't have a copy of GCC to test, but the problem might be the parenthesis around data. The compiler might interpret that as an expression of type DataType, which you couldn't then assign to a reference. Try:

return data;
Peter Ruderman
+3  A: 

No you do not need to use a pointer. You can use a reference or a pointer equally in this case.

The code you pasted should work and does work in g++ 4.4 and Visual Studio 2010.... other than the missing semicolons after the class declarations.

I'm guessing maybe your code here doesn't match exactly the code you are compiling.

In particular did you accidentally do this in code?

class DataType /*: public AbstractDataType*/ { 
public:
   virtual int getInfo() { }; 
};
Brian R. Bondy
Yes, I did indeed actually forget to inherit the AbstractDataType. Jeez, what a newbie error. :-/
Chris Kaminski
@Chris: Happens to everyone one time or another
Brian R. Bondy