Naiem
Naiem

Reputation: 65

How can I declare same object name for different class?

Normally this is my code

#include <iostream>
using namespace std;

class On {
    public:
    int value;
};

class Off {
    public:
    int value;
};


int main() {
    On push;
    push.value = 1;
    cout << push.value << endl;

    return 0;
}

Here is added two classes named On, Off. I want to create the same object name for both classes that something like below. I know the code is wrong but it's for the example of what I'm expecting.

// Full source shown above code
int main() {
    
    On push; // 'push' object for the class -> On
    push.value = 1;
    cout << push.value << endl;

    Off push; // 'push' object for the class -> Off
    push.value = 0;
    cout << push.value << endl; 
    // Here's the problem. How can I can define it's coming from an specific/defferent object?

    return 0;
}

Upvotes: 2

Views: 298

Answers (2)

Thomas Sablik
Thomas Sablik

Reputation: 16448

You can use scopes:

#include <iostream>
using namespace std;

class On {
    public:
    int value;
};

class Off {
    public:
    int value;
};


int main() {
    {
        On push; // 'push' object for the class -> On
        push.value = 1;
        cout << push.value << endl;
    }
    {
        Off push; // 'push' object for the class -> Off
        push.value = 0;
        cout << push.value << endl; 
        // Here's the problem. How can I can define it's coming from an specific/defferent object?
    }

    return 0;
}

Upvotes: 3

ocean
ocean

Reputation: 186

put every one in different namespace :

namespace N1 { On push; }
namespace N2 { On push; }

usage :

 N1::push.value
 N2::push.value

Upvotes: 2

Related Questions