Reputation: 165
I am trying to learn c++ and have to build a code to learn class hierarchy. It is constructed so class A and B have a has-a relationship and class B and C. I need to make a copy of my object in my main file by enabling the copy constructor of A to call the copy constructors in B and C, but I do not know how.
#ifndef A_HH
#define A_HH
#include "B.hh"
class A {
public:
A() { std::cout << "Constructor A" << this << std::endl ; }
A(const A&) { std::cout << "Copy Constructor A" << this << std::endl ; }
~A() { std::cout << "Destructor A" << this << std::endl ; }
private:
B b;
} ;
#endif
Class B:
#ifndef B_HH
#define B_HH
#include <iostream>
#include "C.hh"
class B {
public:
B() { std::cout << "Constructor B" << this << std::endl ; array = new C[len];}
B(const B& other): array(other.array) { std::cout << "Copy Constructor B" << this << std::endl ;
array = new C[len];
for(int i=0;i<len;i++)
{
C[i] = other.C[i];
}
}
~B() { std::cout << "Destructor B" << this << std::endl ; delete[] array;}
private:
C *array;
static const int len = 12;
} ;
#endif
And class C:
#ifndef C_HH
#define C_HH
#include <iostream>
class C {
public:
C() { std::cout << "Constructor C" << this << std::endl ; }
C(const C&) { std::cout << "Copy Constructor C" << this << std::endl ; }
~C() { std::cout << "Destructor C" << this << std::endl ; }
private:
} ;
#endif
I create both objects like this:
#include<iostream>
#include"A.hh"
int main(){
A a;
A a_clone(a);
}
Thus when creating a_clone
, I should get the copy constructor messages, but now it is just creating a new object I think.
Follow-up question: My class B actually looks like the edited one where it has to create a dynamically allocated array of C
objects. But this way it still does not use the copy constructor. How do I fix this?
Upvotes: 3
Views: 738
Reputation: 409186
If you don't have a copy-constructor and let the compiler generate one for you, or if you explicitly add one and mark it as default
(like e.g. A(A const&) = default;
) then the generated copy-constructor should do the right thing for you.
I recommend you read about the rule of zero.
I also recommend you read about copy elision.
Upvotes: 2
Reputation: 5336
In your copy constructors you need to call the copy constructors of the members; for example:
A::A(const A& rhs): b(rhs.b) {}
Upvotes: 2