You are here:

C++/C++ syntax issue

Advertisement


Question
Hi,

I have two objects, call them A and B.  In the class B, I want a const member method which returns a pointer to a const A object.  What is the syntax for this?  I try,

 const A* method(const B& b) const;

But get (from VS .net) the following complaint,

error C2501: 'B::method' : missing storage-class or type specifiers (as well as the warning, missing return type; assumed to be a member function returning 'int').  Now clearly I am not missing a return type, but the compiler is interpreting the method declaration in a manner different from my expectations.  What is the correct form of the declaration?

Many thanks,

Answer
Looking at error C2501 (http://msdn2.microsoft.com/en-us/library/aa983752(vs.71).aspx)  I have to ask you whether you have forward declared class A. Here you use pointer to class A, so you can do:

class A; // <-- note this
class B {
//...
const A* method(const B& b) const;
};

Ofcourse, the definition of class A should be visible to the definition of method. See http://www.informit.com/guides/content.asp?g=cplusplus&seqNum=188&rl=1
If could also refer to Bruce Eckel's book "Thinking in C++" which has both an online and print versions.

Cheers!

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Amit Kumar

Expertise

I can answer Cplusplus language and library questions, including STL, ACE, Boost. I have a good background in Mathematics.

Experience

Programming in CPP for about 8 years. Industry experience of 4 years.

Education/Credentials
Bachelors and Masters in Computer Science from Indian Institute of Technology Delhi.

©2016 About.com. All rights reserved.