0

In case of nested class, how do I access the "Inner" or "Child" class's member function?. For example, the code, where I created "obj1". Now how do I access the "childPrint()" with"obj1"?

example_code:

#include<iostream>
using namespace std;

/////////////////////////////////////////////////
class Parent
{
public:
    void print()
    {
        cout<<"this is from Parent"<<endl;
    }
    class Child
    {
    public:
        void childPrint()
        {
            cout<<"this is from Child"<<endl;
        }
    };
};



int main()
{
    Parent obj1;
    obj1.print();

    Parent::Child obj2;
    obj2.childPrint();

    obj1.Child::childPrint();///ERROR


    return 0;
}
yo only
  • 97
  • 1
  • 2
  • 6
  • 2
    The `Parent` and `Child` classes are still different classes, and don't have any other relation than one being defined inside the other. That only affects the scoping when creating objects of each class (as in `Parent::Child obj2;`) but they still are unrelated. To call `childPrint` you need an instance (an object) of the `Parent::Child` class, and `Parent` is not a `Child`. – Some programmer dude Jul 20 '21 at 08:43
  • 2
    `Parent` doesn't have `Child` members. `Child` and `Parent` are not really connected. – Jarod42 Jul 20 '21 at 08:43

3 Answers3

3

Now how do I access the "childPrint()" with"obj1"?

You can't.

obj1 is of type Parent, which doesn't contain any method called childPrint. An instance of Parent doesn't automatically contain an instance of Child (I think Java does something like this), they are still seperate classes. You can only call this method on an instance of Child.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
1

obj1.Child::childPrint();

In this particular line, you need to understand that childPrint() is an instance member function of class Child. So, only an instance of class Child can call childPrint() function.

If childPrint() function is a static member function(class function) of class Child then it is possible to call it without creating any instance and no error will be shown in Parent::Child::childPrint();.

sushruta19
  • 327
  • 3
  • 12
1

If you have a static method, then you can call it with:

/////////////////////////////////////////////////
class Parent
{
public:
...
    class Child
    {
    public:
    static void childPrint() { cout<<"this is from Child"<<endl; };
    }
}

...

Parent::Child::childPrint();

These are separate classes without any automatic instanciation of child classes and vice versa.

MiniMik
  • 268
  • 1
  • 10