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

(Last Updated On: May 12, 2010)

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


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;


struct PARENT * Kids1=CreateNewInstance();


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

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.
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?

To avoid calling unexpected method (ie: in base class)
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?

using namespace std;

class Base{
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

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:
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:
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),


class Sample
int pV;

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!
Don't miss out!

You will received instantly the download links.

Invalid email address
Give it a try. You can unsubscribe at any time.


Check NEW site on stock forex and ETF analysis and automation

Scroll to Top