Take the 2-minute tour ×

A have a class hierarchy that looks somethign like this:

class AbstractDataType { 
   virtual int getInfo() = 0;

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

class Accessor { 
    DataType data; 
    const AbstractDataType& getData() const { 

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]

share|improve this question
I don't see anything wrong with that code, and Comeau and Visual C++ 2010 both accept it (with trivial changes to get it to compile). –  James McNellis May 19 '10 at 1:31
Works for me with g++ 4.4.1 –  sth May 19 '10 at 1:32
Works on g++ 4.2.4 (modulo the missing semicolons on your class decls) –  Stephen May 19 '10 at 1:34
Besides the missing semicolons after each class definition, there's nothing wrong. It should compile fine. –  jweyrich May 19 '10 at 1:37

2 Answers 2

up vote 4 down vote accepted

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*/ { 
   virtual int getInfo() { }; 
share|improve this answer
Yes, I did indeed actually forget to inherit the AbstractDataType. Jeez, what a newbie error. :-/ –  Chris Kaminski May 19 '10 at 1:50
@Chris: Happens to everyone one time or another –  Brian R. Bondy May 19 '10 at 2:06

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;
share|improve this answer

Your Answer


