Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Abob

Copy constructers with the STL

This topic is 5926 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;
}

  

Share this post


Link to post
Share on other sites
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 );

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!