public: problem

I have a Consumer class with every funcion public.

Then I have a class
MainMenus : public Consumer

One of it's funcions evokes a Consumer funcion, and it works.

But if I take the :Consumer from the MainMenu, it no longer works, saying the funcions are undeclared, although they are public.

Why?
But if I take the :Consumer from the MainMenu

What do you mean by that?
class MainMenus : public Consumer {...};

turns into

class MainMenus {...};
When you remove Consumer you remove the functions it declares.
How come?

If the functions are public, shouldn´t all the other classes be able to acess them?

No.

class MainMenus : public Consumer {...};
This declares MainMenus as a class that publicly inherits the members of Consumer. Public inheritance means that derived classes can use public and protected members of the base class (i.e. OOP regular inheritance).

class MainMenus {...};
This declares MainMenus as a class, period. It has no base class, so any attempt to access members that aren't declared in its body will fail. The class can still access public members of other classes, but not by dereferencing the this pointer.

Ensi wrote:
If the functions are public, shouldn´t all the other classes be able to acess them?


I think you may be getting confused between classes and objects.

In order to access a class function you MUST do so through an object of that class.

so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class A
{
public:

    func() {}
};

int main()
{
    func(); // illegal what object does func() belong to?

    A a; // create an object a of class A

    a.func(); // legal. we know which func to call
}


But when you are writing a class itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class A
{
public:

    func_in_a() {}
};

class B
{
    A a1; // first object of class A
    A a2; // second object of class a

public:

    func_in_b()
    {
        func_in_a(); // illegal, which object of class a to use? a1 or a2?

        a1.func_in_a(); // legal, we are calling the function of a specific object
    }
};


If we want to call the function_in_a() on an object of class B like this:

1
2
3
4
5
6
7
8
9
10
11
12
class B
{
public:

    func_in_b()
    {
        func_in_a(); // illegal, which object of class a to use?
        // It can't be THIS object because THIS object is a B and does
        // not have that function.
    }
};


We have to make A inherit from B:

1
2
3
4
5
6
7
8
9
10
11
class B: public A
{
public:

    func_in_b()
    {
        func_in_a(); // fine. we are calling the function on THIS onject
        // because even though THIS object is a B, it is also an A
    }
};

Topic archived. No new replies allowed.