Tag Archives: copy constructor

C++ source code demo of copy constructor, default constructor, and assignment operator

Another example of Copy Constructor, Default Constructor, Assignment Operator with CONVERSION OPERATOR

#include
using namespace std;

class A {
string s;
public:
A(string str) {s=str;} //constructors must be public
A(A&){} //copy ctr and also does deep copy
A(int iname): x(iname) {}
//int i2=2; // note that you cannot initialize non-const static members in classes
int x;
double d;
operator int() {return x;} //this is a conversion operator

// below is the copy assignment operator,also passed & allows chaining like a=b=c;
// this also demonstrates deep/hard copy
A & operator = (const A & rhs) {
//delete this; this causes program crash
if (this != &rhs) {
//*this = other; // this line can program crash
x=rhs.x;
d=rhs.d;
}
//by convention always return * this
return *this;
}
A() {} //this default ctr is needed because of the 1 argument constructor and has to be public
};

int main() {
string str=”hello”;
A a1;
a1.x=1;
a1.d=2;
A b=a1; //this calls copy ctr
A b2(a1); //this calls copy ctr
b.x=2;
A *c=new A(a1);
c->x=2;
A* d1=new A(a1); //note A* d[10]=new A(a1); causes error

A* d2[10];
for(int i=0;i<10;++i) d2[i]=new A; int i=A(10); //this uses conversion operator (type int) A d3; d3=a1; //this uses copy assignment operator cout<<"d3.x="<FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ concise cheat sheet on copy constructor, default constructor, and assignment operator with sample source code

C++ concise cheat sheet on copy constructor, default constructor, and assignment operator with sample source code
if there exists a derived class Class B:public Class A with another virtual function and class variable of int type. sizeof(B’s obj)=sizeof(A)+sizeof(int). It wil just change the Vptr to point to its virtual function table, it will not allocate another 4bytes for its virtual function rather use one derived from base class.
Base *b = new Derived(); // compiles properly
Nested class in another class. Call by OuterClass::InnerClass
Local class is in a function.
Struct members are public by default while class members are private by default. Both can have contructors.
Assignment operator is used for Shallow Copy by overloading assignment operator.
Copy Constructor is used for Deep Copy
sample x1=x2; //calls copy constructor
sample x1;
x1=x2 ; //calls assignment operator

Dyanamic binding is using virtual functions.
A virtual-table is created for every class having one or more virtual functions. The
virtual table is usually implemented as an array of function pointers where each function pointer corresponds to the various implementations of the virtual function by the derived classes.

When an object of this class is created, it contains a virtual-pointer (v-pointer) which points to the start of v-table. Whenever a virtual function is invoked on this object, the runtime system resolves it by following the v-pointer to the v-table to invoke the appropriate function.
Constructors
Const constructor ensures it does not change the object source. Using const in a copy ctor makes it ready to take both const and non-const arguments. Without const, the copy ctor can only take non-const arguments.
e.g.
Foo::Foo(Foo&){…} // ctor without const
const Foo a;
Foo b(a) //error

You can call a virtual method from a derived class constructor but it would loose its meaning because it will call its own base implementation. This happens because “this” pointer within base constructor(called automatically when derived constructor is called) is of base type and therefore it will call its own implementation and the expected would be of derived.

How many constructor (including copy constructor) and destructors will be called for test1 and test2?

#include
using namespace std;

class Base{
public:
Base(){cout << "Base()" << endl;} Base(const Base&){cout << "Base(const Base&)" << endl;} ~Base(){cout << "~Base()" << endl;} }; Base func(Base b){return b;} void test1(){ Base a; func(a); } void test2(){ Base a; Base b = func(a); } int main(){ test1(); test2(); return 0; } Outputs 3 cons and 3 dest for each function Test1 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() Test2 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() why 3 constructor called for test1 and test2 each Test1 : 1) default will be called at Base a 2) Copy constructor will be called when a is passed to func 3) Copy constructor will be called when b is returned from func Test2 : 1) default will be called at Base a 2) Copy constructor will be called when a is passed to func 3) Copy constructor will be called when b is returned from func Test1 Step-1 Default constructor will be called at Base a; Step-2 Copy constructor will be called when passing a as formal parameter i.e func(a). Step-3 Copy constructor will be called for return object. Step-4 Destructor will be called for actual parameter of func. Step-5 Now this return obj will act as nameless obj in test1() and will get destroy after line func(a) calling destructor one more time. Step-6 Finally Destructor will be called for a. You can see same for test2(); For copy constructor, it has no need to check if it is itself;no return of reference to itself;no need to clean up itself For copy assignment, it needs to check whether it is itself; return; clean up Common: deep or shallow? const Reference argument What is copy constructor? Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you. for example: Boo Obj1(10); // calling Boo constructor Boo Obj2(Obj1); // calling boo copy constructor Boo Obj2 = Obj1;// calling boo copy constructor Conversion constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion. for example: class Boo { public: Boo( int i ); }; Boo BooObject = 10 ; // assigning int 10 Boo object To sum: A copy constructor initialises a new object from an already existing object. An assignment operator is used to copy values from one object to an already existing object. It is a good programming practice to keep the destructor virtual if your base class has any virtual function that is overridden in derived class. Virtual functions are implemented using VTable which is late binding. To create 500 objects, do: TestClass* objects[500]; Now you have 500 pointer to the TestClass objects. now initialize the pointer like - while (i<500) { objects[i] = new TestClass(0); i++; } Do note error results as ISO C++ forbids initialization in array new. Also, If we provide one argument constructor, we "HAVE TO" provide the default constructor otherwise code wont compile at all. Also, you can set arguments explicit with explicit keyword. Constructors cannot be static, virtual, or volatile. To declare array of objects, you can do this, Assume 'Alfa' is class name 1# Alfa *a[10]; // array of 10 pointer to Alfa class for ( i=0; i<10; i++) a[i] = new Alfa(i); //call what ever the constructor you want, put on heap because of new 2# Alfa a[10]; //will give 10 objects on stack. you can do it using double pointers : TestClass **ptr; ptr = new TestClass *[500]; for each i ptr[i] = new TestClass( any int "value"); You can override the new operator by using ‘operator new’ as defined by its functionality. You overload when you need custom memory management.

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview question: Copy Constructor vs assignment operator with const

C++ interview question: Copy Constructor vs assignment operator with const

Structures and classes are the same. The only difference is that structures are defaulted at being public while classes are defaulted at being private. Structures are a C feature so they do not have any C++ features like inheritance.
Copy constructors can overload the assignment operator to allow deep copying instead of default shallow coping. This invoked when one object is initialized to make another.
Both copy constructor and assignment operator are the same where they perform shallow copies by default. As said, you can override the default copy constructor or overload the assignment for deep copies. An KEY DIFFERENCE sample is:
sample x1=x2; //call copy constructor
sample x1;
x1=x2l //calls assignment operator
Copy constructors need a const so that the constructor does not change the state of where it is copying from. This means it cannot be altered within the function. If a function attempts to change the value, the program will not compile. It is advised to use a const in very constructor parameter. Be advised of this potential compiler error:
Foo::Foo(Foo&) {} /constructor without const
const Foo a;
Foo b(a);// error
In a nutshell remember,
1. Copy-Constructor without ‘const’ compiles.
2. Copy-Constructor without ‘const’ is called.
3. ‘const’ in CC prevents passd object from being modified.

There are numerous reasons why you should never call a virtual method from a derived class constructor. This loses its meaning as it will case its base implementation instead.

Also, you should note order of execution in this code:
#include
using namespace std;

class Base{
public:
Base(){cout << "Base()" << endl;} Base(const Base&){cout << "Base(const Base&)" << endl;} ~Base(){cout << "~Base()" << endl;} }; Base func(Base b){return b;} void test1(){ Base a; func(a); } void test2(){ Base a; Base b = func(a); } int main(){ test1(); test2(); return 0; } Output is: Test1 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() Test2 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() Reasons are: Test1 Step-1 Default constructor will be called at Base a; Step-2 Copy constructor will be called when passing a as formal parameter i.e func(a). Step-3 Copy constructor will be called for return object. Step-4 Destructor will be called for actual parameter of func. Step-5 Now this return obj will act as nameless obj in test1() and will get destroyed after line func(a) calling destructor one more time. Step-6 Finally Destructor will be called for a. You can see same for test2();

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!

C++ interview questions including deep copy, shallow copy, copy constructor

Constructor:
How to implement c++’s class’s constructor using the struct in c?

#include
#include

struct PARENT_vtable {
int (*Init)();
int (*Add)();
};

struct CHILD_vtable {
int (*Init)();//child will override
int (*Add)();//parent will define
int (*Sub)();//child will define
};

int parent_doInit()
{
printf(“parent init\n”);
}

int child_doInit()
{
printf(“child init\n”);
}

int parent_doAdd()
{
printf(“parent add\n”);
}

int child_doSub()
{
printf(“child sub\n”);
}

struct PARENT_vtable PARENT_vtbl = {&parent_doInit ,&parent_doAdd };

struct CHILD_vtable CHILD_vtbl = {&child_doInit, &parent_doAdd ,&child_doSub};

struct PARENT_data
{
int x;
};

struct CHILD_data {
int a;
};

struct PARENT
{
PARENT_vtable * vptr;
struct PARENT_data parent;
};

struct CHILD {
CHILD_vtable * vptr;
struct PARENT_data parent;
struct CHILD_data child;
};

struct PARENT * CreateNewInstance()
{

struct PARENT * Cthis = (struct PARENT*)malloc(sizeof(CHILD));

Cthis->vptr =(PARENT_vtable*) &CHILD_vtbl;

return Cthis;
}

main()
{

struct PARENT * Kids1=CreateNewInstance();

((CHILD_vtable*)Kids1->vptr)->Init();
((CHILD_vtable*)Kids1->vptr)->Add();
((CHILD_vtable*)Kids1->vptr)->Sub();

what is all this…i dont understand a word

just use the key word struct instead of class.

struct and class are exactly similar (they both can have constructors). But struct’s members are public by default and class members are private by default.

so declare a struct and have its constructor in its private region.

You need to read the question again!

I am bit confused!!
“Using struct in C”
We have no concept public/private member in C struct.
Moreover, member functions are undefined in C struct.
I might understand the question wrongly so let me clear

Can somebody clarify this question? In C, struct is public, there are no access specifiers in C because data abstraction is an OO concept. So does this imply that we need to mimic OO behavior using struct in C?
@hyan, what did the interviewer say?
@hemant – can you explian your solution?

this is so confusing, someone please clarify this…

his is not confusing. C struct does not allow c++ class features. However, C allows function pointer. Therefore, the point is how to use function pointer to implement c++ constructor concept.
As you can see from the responses more than one person found the question confusing, including myself. I believe it is primarily because of the part of your question that says, ‘using the struct in c?’. This is confusing because c++ has the equivalent of the struct in c. So does the question mean, “How do you do this in c++?” or “How do you do this in c?”

i saw Hemant Jain’s code somewhere before. But I am not very convinced by that. Somebody else has better idea?

Guys, see this link. It is helpful
http://www.keyongtech.com/4831974-how-to-implement-c-class

What is the difference between using Assignment operator and Copy Constructor?

They are the same… In the sense both of them perform a shallow copy by default. You can override the default copy constructor or overload the assignment operator for a deep copy.

“They are the same… In the sense”….should tell you something…apart from the implied difference i thought everyone knew that calling a copy constructor would involve creating a new object whereas an assignment operator could be between two existing objects..

Assignment operator is used for Shallow Copy by overloading assignment operator.
Copy Constructor is used for Deep Copy

sample x1=x2; //calls copy constructor
sample x1;
x1=x2 ; //calls assignment operator

a copy constructor is created by overloading the assignment operator and we can declare and define in the same expression.. whereas this is not possible through assignment operator

Copy Constructor is invoked when initializing an object with another (we can make the copy constructor make a deep copy).

An overloaded assignment operator is invoked when object to object assignment is done.(Again we can make sure that this assignment does a deep copy/assignment).

aka Dynamic binding.

Typically, the pointer’s type determines the function calls. However, virtual functions let the object (not pointer) determines function called.
The base type pointer, calls the method but the proper virtual function at runtime is called (dynamically).

Declare a function as virtual in base class, then override it in each derived class, just like redefining, new function must have same signature. If function declared virtual, can only be overridden. Once declared virtual, a function is virtual in all derived classes. It’s a good practice to explicitly declare virtual though.

Dynamic binding chooses proper function to call of the virtual address table at runtime, but it only occurs off pointer handles. If function called from object, it uses that object’s definition.

I think the answer should be in terms of v-table and v-pointer.

A virtual-table is created for every class having one or more virtual functions. The
virtual table is usually implemented as an array of function pointers where each function pointer corresponds to the various implementations of the virtual function by the derived classes.

When an object of this class is created, it contains a virtual-pointer (v-pointer) which points to the start of v-table. Whenever a virtual function is invoked on this object, the runtime system resolves it by following the v-pointer to the v-table to invoke the appropriate function.

Why do you need the const in a copy constructor? For example, if you have Foo (const Foo &), why do you need the const?
So that the constructor do not change the object from which copy is being made.

Traditionally, const arg to a function signifies that the value passed as const wont be altered within the function (if alteration is attempted, code wont compile).

It is a compilation error to not have const in a constructor that accepts the same object’s reference (aka copy constructor). Having a const reference of same object as the only non-defaulted argument is the signature, which C++ compiler uses to qualify a copy constructor and invoke it for copying between objects.

Lamely said, its to avoid compiler error.

I agree that it is a compilation error to not have const in a copy constructor. But I wonder why? what is the reason behind this choice of the C++ compiler? Can it define the signature being without the const?

I don’t think you will get a compilation error if you don’t have a const in a copy constructor (at least in vc2008 it’s not the case).
IMO, using const in a copy ctor makes it ready to take both const and non-const arguments. Without const, the copy ctor can only take non-const arguments.
e.g.
Foo::Foo(Foo&){…} // ctor without const
const Foo a;
Foo b(a) //error

I guess you sometimes need to take a const object as input, e.g., the unnamed return value from a function. so it makes sense to accept const input.
Reply to Comment
trojanhorse on May 30, 2009 |Edit | Edit

But, a constructor without const is not called a copy constructor, right?

But, a constructor without const is not called a copy constructor, right?

1. Copy-Constructor without ‘const’ compiles.
2. Copy-Constructor without ‘const’ is called.
3. ‘const’ in CC prevents passd object from being modified.

Nothing else.

@Maninder Singh. You rock man…
what do you think all these people have been writing so far…holy crap! OMG…help this poor soul…Jesus!

The copy constructor takes a reference to a const parameter. It is const to guarantee that the copy constructor doesn’t change it, and it is a reference because a value parameter would require making a copy, which would invoke the copy constructor, which would make a copy of its parameter, which would invoke the copy constructor, which …
Reply to Comment

Const is not required in copy constructor, rather it is prefered to have the argument const. The basic reason behind this should be that because the temorary objects created in various operation can be passed to copy constructor.

const has no influence in copy constructor except that it would be resolved at compile time by the compiler. Only thing of importance is passing the argument by reference, if not passed by reference your call to copy constructor will never come back. It would be creating copy for the passed argument, then a temp copy for the copy, another copy of the temp copy and so on…
Why should you not call a virtual method from within a derived class constructor?

http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.5
To avoid calling unexpected method (ie: in base class)
WTF.
you can call virtual methods from derived class constructor. you cannot call virtual methods from base class constructor because, when you are creating the derived class object, first base class constructor is invoked and the base class object type is created. at this time, your derived class object is not yet created completely(only base class object part is created). so calling virtual method can be a problem. thats the reason c++ language doesn’t allow you to call virtual methods in base class constructor.

You can perfectly call virtual methods in derived class constructor becuase the object is created.

You can call a virtual method from a derived class constructor but it would loose its meaning because it will call its own base implementation. This happens because “this” pointer within base constructor(called automatically when derived constructor is called) is of base type and therefore it will call its own implementation and the expected would be of derived.

I think question is wrong.. it should be “Base class” instead on derived class. Calling a virtual function from the derived class is perfectly fine.
How many constructor (including copy constructor) and destructors will be called for test1 and test2?

#include
using namespace std;

class Base{
public:
Base(){cout << "Base()" << endl;} Base(const Base&){cout << "Base(const Base&)" << endl;} ~Base(){cout << "~Base()" << endl;} }; Base func(Base b){return b;} void test(){ Base a; func(a); } void test(){ Base a; Base b = func(a); } int main(){ test1(); test2(); return 0; } 3 ctor 3 dtor for each function No, i think 3 constructors and destructors for test1 and 4 constructors and destructors or test2. in test 2 1. for called for opassing an object to a funs cy value. 2. for retrurning the object by refrence(in func). 3. for initializing a 4. in test 2 1. for called for opassing an object to a funs cy value. 2. for retrurning the object by refrence(in func). 3. for initializing a 4. for initializing b 3 cons and 3 dest for each function Test1 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() Test2 Base() Base(const Base&) Base(const Base&) ~Base() ~Base() ~Base() can anybody explain how r 3 constructors getting called in test1 i can see only 2 one being default constructor and another copy constructor which copies by value blah on October 01, 2009 |Edit | Edit another one for return. 3 Constructor and 3 destructor. @destiny read the "temporary" topic of C++. >> can anybody explain how r 3 constructors getting called in test1 i can see only 2 one being default constructor and another copy constructor which copies by value

A temporary object is created when return b; is called in func() – the return type of func is Base.

Please explain detail..why 3 constructor called for test1 and test2 each

Test1 :
1) default will be called at Base a
2) Copy constructor will be called when a is passed to func
3) Copy constructor will be called when b is returned from func

Test2 :
1) default will be called at Base a
2) Copy constructor will be called when a is passed to func
3) Copy constructor will be called when b is returned from func

Test1
Step-1 Default constructor will be called at Base a;
Step-2 Copy constructor will be called when passing a as formal parameter i.e func(a).
Step-3 Copy constructor will be called for return object.
Step-4 Destructor will be called for actual parameter of func.
Step-5 Now this return obj will act as nameless obj in test1() and will get destroy after line func(a) calling destructor one more time.
Step-6 Finally Destructor will be called for a.

You can see same for test2();

Not sure why test2 has only 4 constructor …

For Base b = func(a), when the 3rd constructor is called to generated the temporary return obj, the temporary obj just get a “new name” – b – so no new copy constructor needed… right?
Reply to Comment
jeet.maninder on November 16, 2009 |Edit | Edit

This is a compilaton error. Because,test1()/test2()doesn’t exists.
And there is redfination of test().

compile and run. Then you will see for yourself. No 4 constructors for test2.

If you want to sound real smart in your interview, you can say that the answer to 3 depends on whether your compiler employs RVO (Return Value Optimization), which it likely thus. In this case, of the Unnamed variety.

It would be 4 otherwise (1 default and 3 copy constructors). But the compiler sees the following

Base b = func(a);
Base func(Base c){return c;}

and rewrites it as

Base b(c);

Simply put, the compiler will construct the temporary inside the space saved for object b.
Reply to Comment
NC-State on January 10, 2010 |Edit | Edit

i agree with above comment…most of the compilers do return value optimization, so that might affect the no of constructor and destructor calls

What are some things to take care of when definining – a) Copy constructor b) Assignment operator?

a. deep copy or shallow copy?
b. check for self assignment or not

deep copy or shallow copy?
While defining copy constr & assigment constr, we need to take care
– Argument must be passed by reference
– properly copy pointers (deep copy)
Reply to Comment

For copy constructor, it has no need to check if it is itself;no return of reference to itself;no need to clean up itself
For copy assignment, it needs to check whether it is itself; return; clean up
Common: deep or shallow? const Reference argument

What about getting an exception in assignment operator

you are right

copy assignment fails, you might get a partial assignment object

int test() {
return 7;
}

int test() {
return 7;
}

There is class having a constructor taking a single int argument (there is no default constructor). Declare an array of 500 objects of that class.

IT is not possible to declare since it is necessary to have default constructor even u might need to call non default constructor

Method 1:
———
include
….
std::vector object_name(500, class_name(value));
….

Method 2:
———
class_name object_name[500] = {class_name(value), class_name(value), …….}
.

Or simply,
Method 1:
———
include
….
std::vector object_name(500, value);
….

use pointers?

like this:

class (*object)[500];

Its simple, we first need to ask a question:
Whats integer vaue should I pass to constructor?
If the ans is support 10,

Objhect *obj = new Object[100] (10);

If the argument has to be decided at run time, then you cannot create an array of sucb a class directly.
create a vector of that Obj* and keep pushing obj* into it.
JS on January 16, 2010 |Edit | Edit

the first approach is wrong.
It gets error:
error: ISO C++ forbids initialization in array new
Reply to Comment
firewithin on November 01, 2009 |Edit | Edit

TestClass test[2] = { TestClass(10),
TestClass(20)};

#include

class Sample
{
private:
int pV;

public:
Sample(int i)
{
pV = i;
}
};

int main()
{
Sample ob[3] = { 0, 0, 0};

Sample *ptrSample = new Sample[100](5);

return 0;
}

Doesnt work dude.
If you dont have a default constructor, you can never initialize a static/ dynamic array/vector (u can use a single argument in vector though)

There are two to create the objects:
TestClass objects[500] = {1,2,3,…,500};
but this is not possible if the number is that high.. so there is another way to create the object…
TestClass* objects[500];
Now you have 500 pointer to the TestClass objects. now initialize the pointer like –
while (i<500) { objects[i] = new TestClass(0); i++; } You can initialize object with the desired value or can change the value later. Now with this approach you have to take care while de-allocating the memory. Anonymous on December 31, 2009 |Edit | Edit I certify your answer. If we provide one argument constructor, we "HAVE TO" provide the default constructor too. Other wise the code wont compile at all. To declare array of objects, you can do this, Assume 'Alfa' is class name 1# Alfa *a[10]; // array of 10 pointer to Alfa class for ( i=0; i<10; i++) a[i] = new Alfa(i); //call what ever the constructor you want. 2# Alfa a[10]; //will give 10 objects on stack. you can do it using double pointers : TestClass **ptr; ptr = new TestClass *[500]; for each i ptr[i] = new TestClass("value"); colingaj on December 09, 2009 |Edit | Edit I believe this is a correct answer, except you need to pass in an int value to TestClass(). Also you will need to ensure that memory is freed appropriately when done! I was asked this yesterday. One trick to remember (and I don't see it here): Make constructor that takes int argument explicit. class TestClass { explicit TestClass(int size) { _ptr = new TestClass[size]; } get() const { return _ptr; } }; Then, do this: TestClass a(500); But what I didnt like abt my solution is the new guy _ptr. This is not working. The compiler still complains "no default constructor" Answer given by shiv is correct. 🙂 Why cannt we use malloc , malloc doesnt invoke a constructor . class Array{ Array(int); } Array *a; a = (Array *)malloc(sizeof(Array) * 500); Mike on January 08, 2010 |Edit | Edit I think this is working! Following is working fine, tested in MSVC++ 6.0, debugged and noticed different addresses in the objects array. // our class class nodefaultctor { int data; public: nodefaultctor(int i) { data = i; } }; // driver program int main(int argc, char* argv[]) { nodefaultctor* obj[500]; for (unsigned int z = 0; z < 500; z++) { obj[z] = new nodefaultctor(0); } return 0; } class Sample { int i; Sample(int k){i=k;} } void createObjects(int 500) { Sample* sample[500]; while(int i<500) { sample[i] = new Sample(i); i++; } } Is static constuctor exist in C++? No. It does in Java. Static constructor can not exist in C++. Who so?? whats a class constructor supposed to be!! isnt that a static constructor ya... its not there !!! You cannot declare a constructor as virtual or static, nor can you declare a constructor as const, volatile, or const volatile. You do not specify a return type for a constructor. A return statement in the body of a constructor cannot have a return value. What is the difference between initializing values using overloaded new and the constructor??? u cannot overload new operator why the hell not? using overloaded new , u gotta first make space, then assign to object, then initialize it... constructor jus initializes the object for u... please distinguish between "new operator" and "operator new" new operator cannot be overloaded; you can only overloaded "operator new" Actually there is a global "operator new" that can be overridden on both a "per class" basis *or* globally overridden. It depends on whether the definition of the operator is within a class scope or the global scope. The default behavior of new is defined in the C++ standard, and does not vary. However, it the behavior if the new operator is overloaded, there is no guarantee that initialization (or that anything at all will happen). The use of the new operator will be governed by, and limited to, whatever functionality is in the overloaded function definition. This question doesn't make sense..If new is overloaded then it has to do whatever the overloaded function is defined as.Constructor will only do initialization without any storage allocation. when you will provide your own copy constructor, assignment operator. give example. when you will provide overloaded new operator. give example 1 example when you want to supply copy constructor, assignment operators is when your class involves ptrs. you can overload new if you have custom 'tracing' for memory leaks, if you use your own memory pooling, etc. Can a copy constructor accept an object of the same class as parameter, instead of reference of the object? No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argument that is an object and not a reference. “Why do u need a copy constructor ?” “Why do u need a copy constructor ?” when you will provide your own copy constructor, assignment operator. give example. What is constructor or ctor? Constructor creates an object and initializes it. It also creates vtable for virtual functions. It is different from other methods in a class. What is copy constructor? Constructor which initializes the it's object member variables ( by shallow copying) with another object of the same class. If you don't implement one in your class then compiler implements one for you. for example: Boo Obj1(10); // calling Boo constructor Boo Obj2(Obj1); // calling boo copy constructor Boo Obj2 = Obj1;// calling boo copy constructor When are copy constructors called? Copy constructors are called in following cases: a) when a function returns an object of that class by value b) when the object of that class is passed by value as an argument to a function c) when you construct an object based on another object of the same class d) When compiler generates a temporary object What is conversion constructor? constructor with a single argument makes that constructor as conversion ctor and it can be used for type conversion. for example: class Boo { public: Boo( int i ); }; Boo BooObject = 10 ; // assigning int 10 Boo object

NOTE I now post my TRADING ALERTS into my personal FACEBOOK ACCOUNT and TWITTER. Don't worry as I don't post stupid cat videos or what I eat!