Subscribe to Invariance_Under_Translation        RSS Feed
-----

Copy Constructors and playing with objects

Icon Leave Comment
Now that a few entries have been posted in regards to OOP we can move on to the topic of copy constuctors. Say we would like to create a bit-wise copy of an object, while performing operations on the copy and keeping the original object intact? This is exactly what our copy constructor will do. Below is a snippet of code that I hope you will find useful, with a few comments throughout. If there are any questions please do not hesitate to ask.

The last function included within, mkBigger, shows how it is possible to return an object to main(). This is accomplished by creating a function of the class that can alter variables within the class, return the result so that once main() calls it's getter to display class data we see the new result.

//Copy Constructor 
//and returning objects
#include<iostream>

using namespace std;


class MyClass
{
	int val;			
	int copyNumber;
public:
	MyClass(int);				//Default Constructor
	MyClass(const MyClass &ob);		//Copy Constructor, const to
	~MyClass();							//ensure object reference always 
	void displayVal(MyClass obj);		//points to MyClass
	int getVal();
	MyClass mkBigger();			//Class function to return object
	
};

MyClass::MyClass(int i)
{
	val = i;
	copyNumber = 0;

	cout<<"Inside Constructor"<<endl;
}

MyClass::MyClass(const MyClass &ob)	//Copy constructot references object 
{									//of MyClass, creating a bit-wise copy
	val = ob.val;						//initialize val to copy of original val
	copyNumber = ob.copyNumber + 1;	//Increment copynumber in copyconstructor 
										//to track which constructor we are in
	cout<<"Inside Copy"<<endl;
}

MyClass::~MyClass()
{
	if(copyNumber == 0)
	{
		cout<<"Destructing Original"<<endl;	//Where we can check clean up 
	}										//of our constructors
	else
	{
		cout<<"Destructing Copy"<<endl;
	}
}

int MyClass::getVal()
{
	return val;
}

void MyClass::displayVal(MyClass obj)
{
	cout<<obj.getVal()<<endl;
}

MyClass MyClass::mkBigger()		//creating a function of MyClass 
{								
		MyClass b(val * 2);		//creates an object that is set explicit 
		return b;					//to multiplying val by 2
}


int main()
{
	MyClass a(10);

	a.displayVal(a);

	a = a.mkBigger();

	a.displayVal(a);

	cin.get();

	return 0;

}

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

January 2018

S M T W T F S
 123456
78910111213
141516171819 20
21222324252627
28293031   

Tags

Recent Entries

Recent Comments

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)