newbie: copy ctor

T

TK

Hi,

is this the right way to write a copy ctor; especially this line:

// copy ctor
B(const B& obj, string c) : obj(c) {

--- my source code ---------------------------------

class A {

public:
A(string a) : s(a) { cout << "ctor A::A()" << endl; }
~A() { cout << "dtor A::A()" << endl; }


private:
string s;
};

//-----------------------------------

class B {

public:
// ctor
B(string a, char *b, string c) : s(a), s1(b), obj(c) {
cout << "ctor B::B()" << endl;
}

// copy ctor
B(const B& obj, string c) : obj(c) {

s = obj.s;
s1 = obj.s1;
}

~B() { cout << "dtor B::B()" << endl; }


B& B::eek:perator=(const B& b) {

if (this == &b) {
return *this;
} else {
s = b.s;
s1 = b.s1;
}
}

private:
string s;
char *s1;

// a class
A obj;
};
 
N

Neelesh

Hi,

is this the right way to write a copy ctor; especially this line:

// copy ctor
B(const B& obj, string c) : obj(c) {

No. A copy constructor for class B must have first parameter of type
B& or const B&, and either there are no other parameters or all other
parameters have default arguments

Examples of copy constructors for a class B are -
B(const B& obj)
B(const B& obj, std::string c = "hello")
B(B& obj)
etc.

Some more suggestions follow -
--- my source code ---------------------------------

class A {

     public:
        A(string a) : s(a) { cout << "ctor A::A()" << endl; }
Since you are using the parameter a for initializing the member
variable s, it would be efficient to have a const reference: A(const
std::string& a) : s(a)
        ~A() { cout << "dtor A::A()" << endl; }

     private:
        string s;

};

//-----------------------------------

class B {

     public:
        // ctor
        B(string a, char *b, string c) : s(a), s1(b), obj(c) {
                cout << "ctor B::B()" << endl;
        }

        // copy ctor
        B(const B& obj, string c) : obj(c) {
Again, having const string& c as second parameter would be efficient.

Also, as discussed above, this is not a copy constructor, this is yet
another constructor.
            s  = obj.s;
            s1 = obj.s1;

It would be a bit more efficient to move these assignments to
constructor initialization list:
B(const B& obj, string c): obj(c), s(obj.s), s1(obj.s1)

Observe that the usage of obj in first term refers to member variable
obj of type A, whereas usage of obj in second term refers to the
parameter of type const B&.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,073
Latest member
DarinCeden

Latest Threads

Top