Copy constructers with the STL

Started by
1 comment, last by Abob 21 years, 11 months ago
I have this example of using a copy constructer with a class that dynamically allocates memory.
  
#include<iostream>
#include<vector>
using namespace std;

class CTest
{
public:
	CTest() { pVal = new int; *pVal = 10;}
        CTest(CTest &c) {pVal = new int; *pVal = *c.pVal;} //copy constructer

	~CTest() {delete pVal;}  

int * pVal;
};


int main()
{
CTest c;
cout << *c.pVal<<"\n";
*c.pVal = 50;
CTest a = c;
*c.pVal = 40;
cout << *a.pVal<<"\n";
cout << *c.pVal<<"\n";
return 0;
}
  
That works fine But when I try to create a vector of CTest’s and use it to initialize another vector it wont compile. If I don’t define a copy constructor and use the compiler default then it works fine. So I think the STL wants a me to overload the copy constructor other then CTest::CTest( CTest & c); But I don’t know what it is Here’s the code that wont work
  

#include<iostream>
#include<vector>
using namespace std;


class CTest
{
public:
	CTest() { pVal = new int; *pVal = 10;}
    CTest(int v){ pVal = new int; *pVal = v;}
	CTest(CTest &c) {pVal = new int; *pVal = *c.pVal;} // copy constructer 

	~CTest() {delete pVal;}  

int * pVal;
};


int main()
{
vector <CTest> v1;

for (int i=0; i<10; i++)
 v1.push_back(CTest(i));
vector <CTest> v2 = v1;
	
return 0;
}

  
Arrg!!
Advertisement
quote:
But when I try to create a vector of CTest’s and use it to initialize another vector it wont compile. If I don’t define a copy constructor and use the compiler default then it works fine. So I think the STL wants a me to overload the copy constructor other then

CTest::CTest( CTest & c);

Try making c a const reference, i.e.

CTest::CTest( const CTest & c );
Thanks it works
Arrg!!

This topic is closed to new replies.

Advertisement