Andres
Andres

Reputation: 275

Create/Initialize new object using variables

I am intending to initialize or create a new object using variables. The error says that i am conflicting declaration.

       //instantiate new node object***********************
        string peer = "peer";
        string pNo = convertInt(addPeerNum); //convert peer number to string to concatenate 2 strings
        string NewPeerObject = peer+pNo; << ERROR POINTS TO HERE
        nodes NewPeerObject; << ERROR POINTS TO HERE

Error message:

conflicting declaration 'nodes NewPeerObject' <-- last line of error 'NewPeerObject' has a previous declaration as 'string NewPeerObject' <-- 2nd last line

My main point is to create a new object when I add more peers. If I addpeer 1, it will create a new object 'peer1' If I addpeer 2, it will be 'peer2' etc.

I am reading in the file which contains

 addpeer 1
 addpeer 100
 addpeer 28

In my program, it reads the file and stores the number in a variable called 'addPeerNum' and with me doing this, it actually has a different string content of 'NewPeerObject'.

So in this instance, i am actually trying to create 3 new objects.

Is there any way which i will be able to do it?

Upvotes: 0

Views: 260

Answers (2)

Dennis
Dennis

Reputation: 3731

I think that what you are looking for is a kind of dynamically resized array of your objects. You can use std::list to achieve that kind of behavior.

std::list<PeerObject> list;
PeerObject peer(peer_string);
list.insert(peer);

or a std::map if you want to use your peer string as a key

std::map<std::string, PeerObject> peer_map;
PeerObject peer(peer_string);
peer_map.insert(peer_string, peer);
//    .... add more
PeerObject& foundObj = peer_map[a_key];
foundObj.doSomething();

You could also do it with MACROs but only at compile time and you should avoid them if possible.

Upvotes: 0

Alok Save
Alok Save

Reputation: 206536

You cannot have two objects with same name like that. It violates the One definition Rule, naturally the compiler complains.
Just please do yourself a favor and change the name of either of them.

Upvotes: 3

Related Questions