Can a variable call a Private function?

Say you are given the following UML class diagram:

Can a variable of type Mystery invoke the function DoSomething()?

I understand that an object (say Mystery X;) could call GetA() to access the private variable int a and to access the public variable int b all you need is X.b but how could this object, X, access the private function DoSomething() if it's even possible?

Answers


I had difficulty understanding exactly what you are asking, but I think I've figured it out.

If you are asking if, given the following declaration:

class Mystery
{
/*...*/
private:
  void DoSomething();
};

you can do something like this:

Mystery m;
m.DoSomething();

...then the answer is no. You cannot call private member functions (or refer to private member variables) from outside the context of the class. Only another member function of Mystery can call the privates. For example:

void Mystery::Foo()
{
  DoSomething();  // this would be possible if Foo() is a member of Mystery
}

EDIT:

Not only can you not call private members from outside the class, you also can't call them from subclasses. For example, this is not valid:

class Base
{
private:
    void Foo() {};
};

class Child : public Base
{
public:
    void Bar() 
    { 
        Foo();  // ERROR:  Can't call private method of base class
    }
};

Need Your Help

TYPO3 Extbase backend module wrong template

module path typo3 backend extbase

I have just installed sample extension called blog_example and i dont understand, that when I open the backend module, i got the frontend template

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.