You are on page 1of 9

C++ - Object Initialization, Member Accessors and Overloading

References

Object
Initializer List Creation &
Initialization
Presentation
Member Member
Accessors access
Assignments
Why do we need
overloading? C++
Initialization, References
Overloading Member Codes
Basics Access and
Overloading
Function
Overloading

Operator
Operator Overloading Friend
Overloading Function
Function
Overloading
Overloading using
Friend Function

1/9
References

They are alias for a variable.

Used to
Modify function parameters
Avoid copying of large structure in function passing
To avoid copy and to modify objects in foreach loop

Refer link Using Reference for more details

//function receiving a reference input


int update(int &x)
{
x++;
}

int main()
{
int num = 10;
int ret = update(num);
}

Problem 1
Consider the case that there is a base class Employee and derived class Manager. Since manager is
also an employee, a derived class object should call its base class constructor. If the base class constructor
in such case requires arguments to get initialized, then how will that be passed ?.

Solution is to use initializer list.

class Base
{
public:
//base class constructor using initializer list
Base(int num):age(num)
{

}
private:
int age;

};
Class Derv : public Base
{
public:
Derv(int num, string inpname):Base(num)
{
name = inpname;
}
private:
string name;

2/9
Initializer List

Initializer list is a comma separated list of values used in constructor to initialize the class members/base
class members.

Following are the use cases.


For initialization of non-static const data members
For initialization of reference members
For initialization of member objects which do not have default constructor
For initialization of base class members
When constructor’s parameter name is same as data member
For better performance
For more details refer Using initializer list

Copy Constructor:

Used to create a new object using an existing object.

Called when
an object of the class is returned by value. // return A(obj), where A is a class
an object of the class is passed to a function by value as an argument.
an object is constructed based on another object of the same class.
compiler generates a temporary object.
Video #1. Copy constructor.mp4

Why should copy constructor argument be always a passed by reference?

Explicit Constructor : To avoid implicit type conversions

Video #2. Explicit Constructor.mp4

Member Accessors

Member functions can be inline or non-inline.

Inline functions
Functions prefixed with keyword inline
Used to avoid function call overhead for small functions
Refer link inline functions

Friend functions

3/9
Have access to private members of a class

Video #3. Friend Function and Class Basics


Friend functions are defined with prefix “friend”.

class Stocks void dispValues(Stocks s)


{
{
public:
Stocks() cout << "Values are :" << s.transType << " " << s.shares << endl;
{
}
transType = "default";
shares = 100; int main()
} {
friend void dispValues(Stocks s); Stocks s;
private: dispValues(s);
string transType; return 0;
int shares; }
};
shares = 100;
Friend} function breaks encapsulation and hence avoid.
friend
Friend void dispValues(Stocks
functions are non-member functions and hence no this pointer argument. Hence need to pass
s);this pointer explicitly.

Problem 2
private:
Case1 : string transType;
int shares;
Software applications are used by admin and by other users. Access rights, the extent of configuration and
use of};application might vary, depending on the user type. An admin user might configure the application with
more parameters, whereas a normal user might configure with only limited/minimal number of parameters.
Consider
voidthat both the user and
dispValues(Stocks s) admin will use the same interface/function for configuration. This will require
atleast{ 2 functions, 1 each for each user type as below.

cout << "In dispValues


int configure(unsigned
transtype share int portno,
are:" << string ipaddress) ; //meant for user
int configure(unsigned
s.transType int portno,
<< " " << s.shares << string ipaddress, int interfaceno , string defaultmask, string
gateway,)
endl;;//meant for admin user
}
Case 2 :

int main()
{
4/9 Stocks s;
dispValues(s);
Extension of Case 1, with an additional requirement say, defaultmask and gateway parameters could be
optional, hence to use default values for the missing parameters. Then configure() is
int configure(unsigned int portno, string ipaddress, int interfaceno , string defaultmask
="255.255.255.0", string gateway= "192.168.1.1") ;//meant for admin user

Case 3 :
Write a function to add the two given inputs. If the inputs are integers/float, perform arithmetic add operation
and return result. If the inputs are strings, then concatenate the strings and return the same. Then it requires
int add(int val1, int val2) ;
float add(float val1, float val2) ;
string add(string val1, string val2) ;
Case 4 :
Consider the need to support 2 implementations of append() say
NODE *append(NODE **head, NODE *data) ;
NODE *append(int data, NODE **head) ; //need to create a node with give data and append to list.
Requirements
Functions with same name, but with different type of arguments
Functions with same name but with variable number of arguments
Functions with same name but different type and order of parameters

In traditional C, it is not feasible to have different functions with same name. But in C++ this is achieved using
function and operator overloading.

Overloading
Ability to create multiple functions with same name and return arguments but with different
implementations based on input arguments ( i.e w.r.t to type/number/order)

Overloading Types
Function Overloading :
float add(float val1, float val2) ;
string add(string val1, string val2) ;

Operator Overlaoding:
Myclass operator+(Myclass obj);

5/9
int operator()(int val);

How is overloading achieved ?


Using name mangling, wherein the compiler generates a unique new name for each overloaded
function. Function call resolution is at compile time.

Function Overloading

class MyClass int main()


{ {
public: MyClass gobj;
// function overloading with def arguments
void Func(int x, int y=20) gobj.Func(3,4);
{ gobj.Func('C');
cout << "x, y is: " << x << ", " << y << endl; gobj.Func(3);// shall use arg2 with default value
} gobj.Func('A', 10.4);

void Func(char prefix, double x=3.14)


{ }
cout << "prefix, x:" << prefix << x << endl;
}
};

Video #1. Function Overloading


Functions with same name and arguments but with differing return type shall not be treated as
overloaded functions

Operator Overloading

int main()
{
Complex c1(10, 5), c2(2, 4), c4(0,3);
//calls operator +
Complex c3 = c1 + c2;

//calls operator ()
c3(10,20);

if (c4) //calls operator bool


{
cout << “c4.real > 0” ;
}
else { cout << “c4.real <=0”;}
return 0;
}

6/9
class Complex
{
public:
Complex(int r = 0, int i =0):real(r), imag(i){}

Complex operator + ( const Complex &obj)


{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag; //prefix and postfix operator overloading
return res; class Myclass
} {
….
Complex operator ()(int real1, int real2) //prefix
{ int operator++()
this->real += ( real1 + real2); {
return Complex(this->real, this->imag); ++this->x;
} }
//postfix operator, val is unsued
operator bool() const int operator++(int val)
{ return (real > 0 ? real : imag);} {
this->x++;
private: }
int real; ..
int imag; }
};

Video #2. Operator Overloading

Points to remember
For member operator functions, left side is this pointer passed as first parameter implicitly.
We cannot change the meaning of an operator when applied to operands of built-in type.
User defined operators cannot be overloaded.
Do not overload &&, ||, comma and address operators.
Return type should be compatible with operator type ( say for logical and relational->bool,
arithmetic->class type etc)
Below operators can’t be overloaded

. Member access or dot operator


?: tertiary or conditional operator
.* pointer to member operator
Sizeof operator
Typeid operator

7/9
Friend Function and Operator Overloading

class Loc;
//…
{
Loc obj1, obj2;
Loc obj3 = obj1 + 2; // can be achieved using overloaded member or friend function
Loc obj3 = 2 + obj1; // can be achieved using overloaded friend function only
Loc obj3 = obj1 + obj2 // can be achieved using overloaded member or friend functions
};

Why should we need to Overloading Stream Operators


To define customized handling for user defined objects
To serialize/deserialize the data objects in file.

Why should overloaded stream operators should be always a friend function ?

Stream objects are global and cannot be made as class members. Hence cannot be passed to member
functions implicitly.
Also stream operator overloading requires stream object as the first argument.

//using friend function


class Complex
{…
friend ostream & operator << (ostream &os, const Complex
&obj); int main()
friend istream & operator >> (istream &is, Complex &obj); {
..};
Complex c1(10, 5), c2(2, 4);
friend ostream & operator << (ostream &os, const Complex &obj); Complex c3 = c1 + c2; // An example call
{
os << obj.real << endl; to "operator+"
os << obj.imag << endl; // c3.print();
}
istream & operator >> (istream &is, Complex &obj) cout << c3;
{ cin >> c3;
is >> obj.real;
is >> obj.imag; cout << c3;
} }

8/9
Summary

Use initializer list and inline functions to enhance performance


Use reference to pass large size data to function
Avoid using friend function to access private members
Use function overloading to achieve compile time polymorphism (w.r.t to data type, number of
parameters, order of arguments).
Overload operators to provide customized handling of basic operators.
Not all operators can be overloaded.
Overloaded functions can be member or friend functions.
Friend functions require this pointer object to be passed as an additional argument.

Reference Codes

Presentation

Assignments

C++ Reference

C++ Libraries

C++ Styleguide

C++ Operator Overloading FAQ

9/9

You might also like