Click here to Skip to main content
15,880,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I asked this question previously but mistyped the key line of code. I couldn't figure out how to modify it so I deleted it and am reposting it. My apologies if this is not the done thing.

class Thing
{
public:
   Thing() {}
...
};

class Blah
{
public:
  const Thing* GetThing() const;

private:

   Thing* GetThing(); 
};


void anotherclass::function(Blah& b)
{
   const Thing* thing = b.GetThing();
}


Gives the error 'Cannot access private member'.

Can anyone tell me why?

If I cast b to be const Blah& it's fine but I'm just interested why VS doesn't resolve the call to the public const version of GetThing()?
Posted
Comments
Dalek Dave 23-Jul-10 10:31am    
I see you remembered the Code Block :)

The parameter of anoterclass::GetThing is Blah& that is not const.
Hence b.GetThing() resolve to the non-const function, that exist, but it is private.

Making a function private makes it not accessible, but doesn't remove it from the declaration scope.

try

C++
void anotherclass::function(const Blah& b)
{
   const Thing* thing = b.GetThing();
}
 
Share this answer
 
If you cast b to const Blah& then you can call only methods declared as const, i.e. that cannot modify the internal state of the object. In this case the choice is for const Thing* GetThing() const.

But it will continue to work if you write:

C#
class Thing
{
public:
   Thing() {}
...
};

class Blah
{
public:
  Thing* GetThing() const;

private:

   Thing* GetThing();
};


void anotherclass::function(Blah& b)
{
   const Thing* thing = b.GetThing();
}


This will continue to work because is safe to implicitly add the const attribute to a variable, whereas it is not safe the opposite.

In your code, the compiler choose which version of your method to use depending on the fact that b is const or not.
 
Share this answer
 
v3
Comments
[no name] 26-Jul-10 3:46am    
But then the public interface exposes the Thing* as non-const which is not what I want
Sauro Viti 26-Jul-10 4:08am    
Yes, you are right; I show this example to point out that the compiler resolve the method to be called without regard to the returned type
Thanks to those who replied.

From the c++ spec...

13.3.1.4:
For non-static member functions, the type of the implicit object parameter is reference to cv X where X is
the class of which the function is a member and cv is the cv-qualification on the member function declara-
tion. [Example: for a const member function of class X, the extra parameter is assumed to have type ref-
erence to const X. ]

Then according to 13.3.3.1.1, the const variant would count as a "conversion", and thus be a worse fit.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900