Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner Class access to Outer Class members

Tags:

c++

I'm very confused about this topic, basically I've this code:

template <typename T>
class SListArray
{
public:
    class const_iterator
    {
    public:
        const_iterator(size_t i_currentNode = -1)
            :m_position(i_currentNode)
        {
        }

        T const& operator*() const
        {
            return m_data[m_position].element;
        }

        // ...

    protected:
        size_t m_position;
    };

    explicit SListArray();

    // ...

private:
    std::vector<Node<T>> m_data;

    // ...
};

This code give me a compiler error, so, I would to know if is possible to give the Inner Class the acces to the members of the Outer Class.

Thanks.

like image 841
enigma Avatar asked Apr 20 '11 14:04

enigma


People also ask

How does an inner class instance access the outer class members?

Since inner classes are members of the outer class, you can apply any access modifiers like private , protected to your inner class which is not possible in normal classes. Since the nested class is a member of its enclosing outer class, you can use the dot ( . ) notation to access the nested class and its members.

Can inner class access outer class public variables Java?

Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class. Since inner classes are associated with the instance, we can't have any static variables in them.

Can inner classes access outer class members C++?

An inner class is a friend of the class it is defined within. So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer .

Can an inner class be accessed from outside package?

Unlike a class, an inner class can be private and once you declare an inner class private, it cannot be accessed from an object outside the class.


1 Answers

Nested classes already have access to the containing class's members, assuming they have a pointer/reference to the containing class upon which to operate. Your iterator will need to store a reference to the outer class in order to be able to access the container as you appear to want.

Also note that protected data is usually a code smell and should typically be avoided. Prefer private data and a protected interface if appropriate.

EDIT: Unless this is strictly an exercise to learn how to program a container, just use one of the C++ standard containers such as vector which are well developed, debugged, and optimized.

like image 96
Mark B Avatar answered Oct 12 '22 01:10

Mark B