Call constructors for calling member functions
I am trying to learn C ++ and have to create some code to learn the class hierarchy. It is built in such a way that 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, including the copy constructor A to call the copy constructors in B and C, but I don't know if how to do it.
#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);
}
So, on creation, a_clone
I have to get copy constructor messages, but now it's just creating a new object which I think.
Follow-up question: my class B really looks like the edited one where it should create a dynamically allocated array of objects C
. But this way it still doesn't use the copy constructor. How to fix it?
source to share
If you don't have a copy-constructor and let the compiler generate it for you, or if you explicitly add it and mark it as default
(for example A(A const&) = default;
), then the generated copy-constructor should do the right thing for you.
I recommend that you read the zero rule .
I also recommend that you read about copy elision .
source to share