Greg M
Greg M

Reputation: 954

Access typedef in classes with an object, not the scope resolution operator (::)

In the following code, when I try to access the typedef with an instantiated object, it gives me an error, when I access it using the scope resolution operator (::), the program works perfectly. I just wanted to know why.

#include <iostream>

class Types {

    public:

        typedef int Integer;

};

int main() {

    Types types;

    types.Integer foo = 1; // <-- Gives me an error

    Types::Integer goo = 2; // <-- Works perfectly fine

    std::cout << foo;
    std::cout << std::endl;
    std::cout << goo;

    return 0;

}

I'm just using this as an example, this is not real code to anything. The error it is giving me is:

Line 15 | invalid use of 'Types::Integer'

Upvotes: 0

Views: 911

Answers (1)

Shoe
Shoe

Reputation: 76240

It's just how the syntax works. Integer in that context is a type belonging to the Types namespace, and if you want to access that type you have to use ::. operator. is used for member access of objects or functions.

operator. allows you to access a member belonging to an instance, while :: traverses namespaces (allowing you to access static fields, static functions, typedefs, member variables, etc.).

Upvotes: 3

Related Questions