Soumyajit Roy
Soumyajit Roy

Reputation: 463

Can't access inner class member with outer class object

#include <iostream>

class Outer
{
    int o;
public:
    void setOuter(int o)
    {
        this->o=o;
    }
    class Inner
    {
    public:
        int i;
        int retOuter(Outer *obj)
        {
            return obj->o;
        }
    };
};

int main(int argc, char **argv) {
    Outer::Inner obj;
    obj.i=20;
    std::cout<<"Inner i = "<<obj.i<<std::endl;

    Outer *obj1=new Outer;
    obj1->setOuter(40);
    std::cout<<"Outer o = "<<obj.retOuter(obj1)<<std::endl;

    obj1->Inner::i =50; //Access the inner class members by Outer class object!
}

Everything in the above code is fine apart from the last line. Why I am not able to access the Inner class member with an Outer class object? Outer class object should have all the public member access of class Outer And how is the behavior when I create an Inner class object as it is contained by an Outer class!

Upvotes: 0

Views: 535

Answers (1)

Luchian Grigore
Luchian Grigore

Reputation: 258548

Inner is just a class defined at a different scope. It's no different than saying

class Inner
{
public:
    int i;
    int retOuter(Outer *obj)
    {
        return obj->o;
    }
};

and then

Inner::i =50

which obviously isn't possible because i isn't static.

Declaring an inner class doesn't automagically declare a member of that type for the outer class which you can access using that syntax.

Now, something like:

class Outer
{
    int o;
public:
    void setOuter(int o)
    {
        this->o=o;
    }
    class Inner
    {
    public:
        int i;
        int retOuter(Outer *obj)
        {
            return obj->o;
        }
    } innerMember;
    //    ^^^
    // declare a member
};

int main(int argc, char **argv) {
    Outer *obj1=new Outer;
    obj1->innerMember.i =50; //Access the inner class members by Outer class object!
}

would work.

Upvotes: 5

Related Questions