Tag Archives: assignment operator

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 question including operators like conversion operator and assignment operator

Operators:
What’s the difference between assignment operator and copy constructor

copy constructor can do a deep copy whereas assignment is merely a shallow copy ie references.
wrong…
When not provided, compiler will provide both; which does bitwise copy

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.
The key difference here is that for assignment operator the target object already exists.
Right, that’s from Effective C++

I think the difference lies in the fact that using a copy constructor allows you to make a deep copy while the assignment operator only makes a shallow copy.

A sample code for copy constructor.. though i have not made use of it for making a deep copy.. will post it soon

#include
#include
#include
using namespace std;

struct copy_variable
{
public:

int abc_1;
int abc_4;
char abc_2;
char abc_3[10];
copy_variable()
{
}
copy_variable(const copy_variable& some_object):abc_2(‘a’),abc_1(1000)
{
abc_1 = some_object.abc_1;
strcpy(abc_3,”something”);
abc_4 = 0;
cout<<"The values of abc_1, abc_2, abc_3\n" <
#include
#include
using namespace std;

struct copy_variable
{
public:

int abc_1;
int abc_4;
char abc_2;
char abc_3[10];
copy_variable()
{
}
copy_variable(const copy_variable& some_object):abc_2(‘a’),abc_1(1000)
{
abc_1 = some_object.abc_1;
strcpy(abc_3,”something”);
abc_4 = 0;
cout<<"The values of abc_1, abc_2, abc_3" <<"\t"< 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!