Creep2DJ Creep2DJ - 3 months ago 9
C++ Question

Declaring multiple objects of different classes with the same name

Is it OK for me to declare multiple objects with the same name, but in different classes? Or will this throw everything into chaos? Let me include some code to help understand what I want to do:

class get{
public:
string info(){
int str; cin >> str;
return str;
};
};
class store{
public:
string data;
}

int main(){
get foo;
store foo;

foo.data = foo.info();

cout << foo.data;

return 0;
}


Note that this isn't necessarily the code that I'm using, just an example. If I need to elaborate, please tell me. Thanks, all!

Answer

You may not declare two objects with the same name in the same scope. The compiler will issue an error.

However for example this code is valid

#include <iostream>
#include <string>

class get
{
public:
    std::string info() const 
    {
        std::string str; 
        std::cin >> str;
        return str;
    }
};

class store
{
public:
    std::string data;
};

store foo;

int main()
{
    get foo;

    ::foo.data = foo.info();

    std::cout << ::foo.data << std::endl;

    return 0;
}

because two objects with the same name are defined in different scopes and there are used qualified names.

Also you may declare an object wuth the same name as the name of a class in the same scope. For example

store store;

In this case the name of the object hides the name of the class.

Comments