-
May 9th, 2013, 01:59 AM
#1
copy constructor issues with vector class
Hey there. Newbie c++ student here. I am experiment with copy constructors and STL containers. I made a test class A and gave it an assignment operator and a copy constructor. I then instantiated an object of type A and then a vector to hold objects of this class A. Then I used push_back method to insert an instance of A and I get an error in Visual C++ 2010 that breaks to the push_back implementation in vector.cpp.
Code:
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
A();
A(int a, int b);
~A();
A(const A& src);
A operator= (const A &rhs);
private:
int a;
int * b;
};
A::A()
{
a = 0;
b = nullptr;
cout << endl << "A 0 argument constructor called";
}
A::A(int a, int b)
{
this->a = a;
this->b = new int;
*this->b = b;
cout << endl << "A 2 argument constructor called";
}
A::~A()
{
a = 0;
delete b;
cout << endl << "A destructor called";
}
//There is a problem with this copy constructor
A::A(const A& src)
{
this->a = src.a;
this->b = new int;
*this->b = *src.b;
cout << endl << "A copy constructor called";
}
A A::operator= (const A &rhs)
{
A tempA(rhs.a, *rhs.b);
return tempA;
}
int main()
{
A a1(1, 2);
A a2;
vector <A> v1;
v1.push_back(a1);
v1.push_back(a2);
system("pause");
return 0;
}
Object a1 adds just fine into the vector v1, but a2 does not. The problem seems to be with the fact that it was instantiated with my provided 0 argument constructor which assigns the pointer member to nullptr. Here is the output before the debugger breaks:
"
A 2 argument constructor called
A 0 argument constructor called
A copy constructor called
A copy constructor called
A destructor called
"
Now. when I change the default constructor A::A() to assign a memory using "new int" and assign a value to the int, then it adds just fine to the vector and the following output is produced:
"
A 2 argument constructor called
A 0 argument constructor called
A copy constructor called
A copy constructor called
A destructor called
A copy constructor called
"
Something is going on with the pointer in A::A() and I cannot figure out what it is after having read through some copy pointer tutorials. Your debugging help is appreciated. Knowing whats wrong will deeply improve my knowledge of C++
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|