Subhamoy S.
Subhamoy S.

Reputation: 6764

Copy Constructor with No Arguments

have written this little class, which generates a UUID every time an object of this class is created.

#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>    

class myClass {

public:

    boost::uuids::uuid GetUUID();

    virtual ~myClass();

    myClass() {   // constructor
        mId = boost::uuids::random_generator()();
        std::cout<< "object created with uuid " << mId <<std::endl;
    }

private:

    boost::uuids::uuid mId;

}

At some point, I am pushing these objects to a vector and equating that vector with another vector using simple assignment operator. To ensure the objects in the new vector do not generate new UUIDs, I want to write a copy constructor. But as you can see, the constructor needs no arguments. So I am not sure how to write the copy constructor. Moreover, if I have multiple variables instead of just one UUID, how do I handle that situation?

Upvotes: 0

Views: 1076

Answers (3)

Sdra
Sdra

Reputation: 2357

In this case the default copy constructor and assignment operator generated by the compiler should do what you expect, so you don't need to define it explicitly.

Upvotes: 0

Torsten Robitzki
Torsten Robitzki

Reputation: 2555

The compiler will generate a copy constructor and an assignment operator for you. If the only thing this operations have to do, is to copy all members, then the compiler generated operations will exactly do this. If not, the signature for a copy constructor is:

myClass( const myClass& other )

The signature for the assignment is:

myClass& operator=( const myClass& other )

kind regards

Torsten

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258698

You need the following signature:

 myClass(const myClass& other)
 {
     mId = other.mId;
 }

and also the assignment operator

 myClass& operator=(const myClass& other)
 {
     mId = other.mId;
     return *this;
 }

Note that if you don't implement these, the compiler-generated ones will do a shallow copy, so no new UUIDs will be generated. But you should have them there to obey the rule of three (you do have a destructor after all).

Upvotes: 5

Related Questions