Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ private members accessible? [duplicate]

Tags:

c++

I have this project in our signals class which uses C++. I was tinkering with our instructors code when I saw this:

ListData::ListData(const ListData& newlist) 
    : Data(), nbNodes(newlist.nbNodes) {}

This is a "copy constructor" as he says, and should be roughly equivalent to the following:

ListData::ListData(const ListData& newlist){
  Data = "";
  //copy nbNodes of newList to current instance
  nbNodes = newlist.nbNodes;
}

But what bothers me is that nbNodes is a private member. How could this constructor access the nbNodes of the passed newList if it's private?

like image 703
Joseph Avatar asked Feb 27 '13 14:02

Joseph


1 Answers

An interesting thing about private members is that two objects of the same type can access each others private members freely. You can think of it as a class is always friends with itself. Since this is the constructor for ListData and newlist is also a ListData, you can access its privates just fine.

Here's an example of this:

#include <iostream>

class foo
{
  public:
    foo() { }
    foo(std::string secret) : secret(secret) { }
    void steal_secret(const foo& other) { secret = other.secret; }
    std::string get_secret() { return secret; }
  private:
    std::string secret;
};

int main() {
    foo f1("I'm actually a bar");
    foo f2;
    f2.steal_secret(f1);
    std::cout << f2.get_secret() << std::endl;
    return 0;
}

f2 happily and easily steals the secret from f1, despite it being private.

The reason for this being allowed is simply because private doesn't mean private to an object - it means private to a class. This eases the implementation of functions such as copy constructors that require doing some work to the internals of two objects of the same class.

The rule comes from the definition of private (§11/1):

A member of a class can be

  • private; that is, its name can be used only by members and friends of the class in which it is declared.
  • [...]

Note that it is defined in terms of classes and not objects.

like image 95
Joseph Mansfield Avatar answered Oct 02 '22 01:10

Joseph Mansfield