Sie sind auf Seite 1von 68

Advanced concepts with Classes

The features of c++


Inline members functions
• The inline functions advise the compiler to insert
the copy of the function’s code inline within the
code of the calling function
• The syntax
▫ Inline <return_type> <function_name>
(parameter_list)
{
 //body of the inline function
 Return;
}
• They save memory space as all the function calls
to be specified
• The following activities make the inline function
slower & inefficient
▫ Values must be copied into storage of function
pointer
▫ Machine register must be shaved
▫ Transfer of control to the function
▫ Return value
▫ Returning control back to the calling function
Example:-
#include <iostream.h>

inline float square (const float x) //inline function definition


{
return (x*x);
}

void main()
{
float num, sqr;
cout << "Enter a number"<<endl;
cin >> num;

sqr = square (num); //function call

cout <<"Square of " << num << " is "<< sqr <<endl;
}
Example:-
#include <iostream.h>

inline float cube (const float x) //inline function definition


{
return (x*x*x);
}

void main()
{
float num, cub;
cout << "Enter a number"<<endl;
cin >> num;

cub = cube (num); //function call

cout <<“Cube of " << num << " is "<< cub <<endl;
}
Note
• Inline function can reduce execution time
• This should be used for only small but frequently
used functions
• Inline may not work on looping such as swith,
goto
• Inline functions are recursive
Friend
• The private members of a class cannot be
accessed by the non-members functions
• This can be archived by using friend keyword
Example:-
#include <iostream.h>
class ff
{
private: int x;
int y;

public: void accept (void)


{
cout <<"Enter the values"<<endl;
cin >> x >> y;
}

friend int average (ff num);


friend int largest (ff num);

}; //End of class definition


//friend functions
int average(ff num)
{
return ((num.x + num.y) / 2.0);
}

int largest (ff num)


{
if (num.x > num.y)
return num.x;
else
return num.y;
}
void main()
{
ff cob; //object creation

cob.accept();

cout <<"Average = "<<average(cob)<<endl;


cout <<"Largest = "<<largest(cob)<<endl;
}
Note
• The keyword friend is used to declare friend
functions
• A friend function is called just like normal functions
• A friend function is not in scope of the class to which
it have been declared
• A friend function can be declared in private or
public section
• Usually friend has a objects as its arguments
• A friend function cannot access the class members
directly. An object name followed by dot operator
The implicit this pointer
• Each object declared has its own copy of data
members
• There is only one copy of members functions &
each object as a pointer which holds address of
object itself
• The pointer is called this
▫ The this is a built-in pointer
▫ This pointer also used to access data members
▫ Treated just like ordinary pointer
▫ This will be use full in returning values
Example:-
include <iostream.h>

class number
{
private: int x;

public: void setValue (int d)


{
this->x = d;
}

void displayValue(void)
{
cout <<"x = "<< this->x <<endl;
cout <<"Address of the object = "<<this<<endl;
}

};
void main()
{
number n1, n2; //object creation

n1.setValue(30);
n2.setValue(80);

n1.displayValue();
n2.displayValue();

}
Static class members
• Static is the keyword
• The value will be retained
• The static keyword declared with data members
are called static data members
• The members functions are called static member
function
Static data members:
• When you precede a member variable’s declaration with static,
you are telling
• The compiler that only one copy of that variable will exist and that
all objects of the class will share that variable.
• Unlike regular data members, individual copies of a static
member variable are not made for each object.
• No matter how many objects of a class are created, only one copy
of a static data member exists. Thus, all objects of that class use
that same variable.
• All static variables are initializes to zero before the first object is
created.
• When we declare a static data member within a class, we are not
actually defining it. (that is, you are not allocating storage for it).
• Instead, you must provide a global definition for it elsewhere,
outside the class. This is done by re-declaring the static variable
using the scope resolution operator to identify the class to which it
belongs.
• This causes storage for the variable to be allocated
Define global for static data members
• Syntax
▫ Data_type class_name:: varable_name;
• Advantages
▫ It does not create any names conflict with the
global objects declared in the program
▫ It enforces data hiding.
Example:-
#include <iostream.h>
class sdataItem
{
private: static int count;
int numb;

public: void readData (int ival)


{
numb = ival;
count = count + 1;
}

void displayCount(void)
{
cout <<"Count = ";
cout <<count<<endl;
}

}; //End of class definition


int sdataItem :: count=5; //static member definition
void main()
{
sdataItem x,y,z; //object creation

x.displayCount();
y.displayCount();
z.displayCount();

x.readData(13);
y.readData(27);
z.readData(38);

cout <<"After inputting values"<<endl;


x.displayCount();
y.displayCount();
z.displayCount();

} //End of main
Static member function
• The static member function will act on static
data members
• Remember points
▫ This will address only the static data members
▫ This does not have this operator
▫ Using dot operator we can access the public data
members
Example:-
#include <iostream.h>
class checkObject
{
private: static int num;

public: static int totalObjects(void)


{
num = num + 1;
return num;
}

void display (void)


{
cout <<"Object "<<num<<" is created so count = "<<num <<endl;
}

};
int checkObject :: num = 0;
void main()
{
checkObject cob1;
checkObject :: totalObjects();
cob1.display();

checkObject cob2;
checkObject :: totalObjects();
cob2.display();

}
Dynamic
• The object are created & destroyed at run-time
since the objects are allocated & de-allocation
during the execution of a programs they are
called dynamic allocated objects
▫ A dynamically allocated objects is allocated on the
free space
▫ A dynamically allocated objects created using
 new expression
▫ A dynamically de-allocation object using
 Delete expression
• A dynamically allocated objects may be single or
array of objects
Dynamic allocation
• The process of allocating & de-allocating memory
to the objects during the execution of a program
is referred to as dynamic memory allocation
▫ Using new
• Unnamed objects
▫ Ex:- int *ptr=new int;
• Un-Initialized memory
▫ Ex:- int *ptr1=new int(0);
▫ Ex:- int *ptr2=new int(5);
De-allocation memory
• The memory allocated to the objects from the
free store is de-allocated
▫ Using delete
▫ delete ptr;
• Applying a delete expression to the same
memory twice will cause error
• We should place delete at last memory other
wise cause leak of memory
Example:-
#include <iostream.h>

void main()
{
int *iptr = new int(100);
float *fptr = new float(30.25);
char *cptr = new char('p');

cout <<"Object with int value is " <<*iptr<<endl;


cout <<"Object with float value is " <<*fptr<<endl;
cout <<"Object with char value is " <<*cptr<<endl;

delete iptr;
delete fptr;
delete cptr;
}
Dynamic allocation & de-allocation of
arrays

• Dynamic using new & delete


• New
▫ Ex:- int *ptr=new int[10];
▫ Ex:- int (*ptr)[15]=new int[15][15];
• Delete
▫ Ex:-delete[] ptr
Example:
#include <iostream.h>
void main()
{
int *ptrA = new int[10]; //array of 10 integers
int *pN = new int;
int *psum = new int(0);
int i, j;
cout <<"Enter the number of elements "<<endl;
cin>> *pN;
cout<<"Enter the elements one by one"<<endl;
for( i = 0; i < *pN; i++)
{
cin >> ptrA[i];
}
cout <<"The give array elements are"<<endl;
for(i = 0; i < *pN; i++)
{
cout << ptrA[i] <<endl;
}
for( i = 0; i < *pN-1; i++)
{
*psum=*psum+ptrA[i];
}
cout<<“The sum of array is"<<*psum<<endl;

delete pN;
delete psum;
delete[] ptrA;
}
References
• It is new data kind of variable
• It provides an alias for previous defined variable
▫ Syntax
 Data_type & reference_name=variable_name;
 Ex:-float f=100;
 Float &sum=total;
Example:
#include<iostream.h>
Void main()
{
int x=5;
int &y=x;
cout<<“x=“<<x<<endl;
cout<<“y=“<<y<<endl;
x++;
cout<<“x=“<<x<<endl;
cout<<“y=“<<y<<endl;
}
Ex:-1 int x=100; int &y=; y=x; error
Ex:-2 int a=10; int &ref1=a,&ref2=a;
Ex:-3 char *ptr=“hello”; char &*refptr=ptr;
Ex:-4 int x,y,z; int &arr[3]={x,y,z}; error
Functions
• Syntax
▫ Return_type function_name(parameter_list)
{
 //body of function;
}
• Small sub-routine of a program
▫ Pass by value
▫ Pass by pointer
▫ Pass by references
Pass by value…
#include <iostream.h>
void main()
{
int x,y;
void swapxy (int a, int b); //Function prototype
cout<<"Enter the values of x and y"<<endl;
cin >> x >> y;
cout <<"x= " <<x<<" and y = "<< y <<" (Before swapping) "<<endl;
swapxy(x,y);
}
void swapxy(int a, int b)
{
int temp;
temp = a;
a = b;
b = temp;
cout <<"x= " << a <<" and y = "<< b <<" (After swapping) "<<endl;
}
Pass by pointer
#include <iostream.h>
void main()
{
int x,y;
void swapxy (int *px, int *py); //Function prototype
cout<<"Enter the values of x and y"<<endl;
cin >> x >> y;
cout <<"x= " <<x<<" and y = "<< y <<" (Before swapping) "<<endl;
swapxy(&x,&y); //function call
cout <<"x= " <<x<<" and y = "<< y <<" (After swapping) "<<endl;
}
void swapxy(int *px, int *py)
{
int temp = *px;
*px = *py;
*py = temp;

}
Passing by references
#include <iostream.h>
void main()
{
int x,y;
void swapxy (int &xref, int &yref ); //Function prototype
cout<<"Enter the values of x and y"<<endl;
cin >> x >> y;
cout <<"x= " <<x<<" and y = "<< y <<" (Before swapping) "<<endl;
swapxy(x,y); //function call
cout <<"x= " <<x<<" and y = "<< y <<" (After swapping) "<<endl;
}
void swapxy(int &xref, int &yref )
{
int temp = xref;
xref= yref;
yref = temp;
}
Differences between
• Reference • Pointers
• A reference must be • A pointer can point to
initialized once it is different object or no object
initialized to one object, it • A function with pointer
can never made to refer to cannot dereference the
another object pointer unless it checks that
• A function with reference the pointer is pointing the
parameter does not require object
to check against reference • A pointer parameter is
object prefixed with * operator
• A reference parameter is • It is not used in
prefixed with & operator implementing overloading
• It help in implementing functions
overloading functions
Constructors
• The constructors is a special kind of member
function which is used to initialize the data
members automatically
• So it got the name constructors

Class box
{
private: int l,w,h;
public: box() { l=0;w=0;b=0; }
};
Characteristics of a constructors
• A constructors have the same name as that of
class
• A constructors is declared in the public section
of the class definition
• A constructors is invoked automatically as soon
as the class object is created
• A constructors does not have any return value
• The programmer does not have control over
constructors
• The constructors are not inherited
• A constructors cannot be declared virtual
• Constructors can be overloaded
Constructors
• There are three types of constructors
▫ Default constructors
 Ex: box(){ }
▫ Parameterized constructors
 Ex: box (int I, int j, int k)(l=I;w=j;b=k;}
▫ Copy constructors
 Ex: box(box &b){ l=b.l;w=b.w;b=b.b;}
Default constructors
#include <iostream.h>
class box
{
private: int length;
int width;
int height;
public: box() //constructor
{
length = 0;
width = 0;
height = 0;
}
void print(void)
{
cout <<"Length = "<<length<<endl;
cout <<"Width = "<<width <<endl;
cout <<"Height = "<<height<<endl;
}

}; //End of class box


Parameterized
#include <iostream.h> constructors
#include <string.h>
class employee
{
private: int empcode; char empname[20]; float salary;
public: employee(int eno, char name[], float sal) //constructor
{
empcode = eno; strcpy(empname, name); salary = sal;
}
void display()
{
cout <<"Employee information "<<endl;
cout <<"Employee code = "<<empcode <<endl;
cout <<"Employee name = "<<empname <<endl;
cout <<"Employee salary = "<<salary<<endl;
}
};
void main()
{
employee emp = employee(1234, "Prabhu", 20000);
emp.display();
}
Overloading constructors
#include <iostream.h>
class point
{
private: int x;
int y;
public: point() //default constructor
{ x = 0; y = 0; }
point (int xp, int yp) //parameterized constuctor
{
x = xp;
y = yp;
}
void display()
{
cout <<"x = "<<x <<"\t"
<<"y = "<<y <<endl;
}

}; //End of class point


void main()
{
point P1, P2(10,20); //objects P1 and P2 are created
cout <<"Point P1 is "<<endl;
P1.display();
cout<<"Point P2 is "<<endl;
P2.display();
}
Copy constructor
• A copy constructor is used to initialize an object
from another object;
▫ Ex: box b1;
▫ Box b2(b1); or box b3=b1;
▫ B2=b1; will not invoke the copy constructor
• A copy constructor takes a reference to an object
of the same class as itself as an argument
Example:
#include<iostream.h>
#include<conio.h>
Class code
{
int id;
public:
code() { }
code(int a){ id=a;}
code(code &a){ id=a.id;}
void display()
{ cout<<id;
}
};
Void main()
{
code a(100);
code b(a);
code c=a;
code d;
clrscr();
cout<<“id of a:”;a.display();
cout<<“id of b:”;b.display();
cout<<“id of c:”;c.display();
cout<<“id of d:”;d.display();
getch();
}
Destructor
• A destructor is a special member function which
de-allocate the memory
• It has the same name of the class but with
(tilde)~ symbol
• Ex: ~sample(){ }
Characteristics of a destructors
• A destructor is invoked automatically by the
compiler upon exit of program
• A destructor does not return the value
• A destructor cannot be declared as static, const
• A destructor must be declared in public section
• If the constructor use new to allocate the
memory then delete should be used to de-
allocate the memory
#include <iostream.h>
class sample
{
private: int x;
public: sample() //constructor
{
x = 0;
cout <<"In constructor, "
<<"x = "<< x <<endl;
}
void printx()
{
cout <<"In printx, x = "<< x <<endl;
}
~sample() //Destructor
{
cout <<"In desructor. Object dies"<<endl;
}

}; //End of class sample


void main()
{
sample s1;
s1.printx();
}
How the execution of constructors&
destructors
#include <iostream.h>
class sample
{
public: sample(void) //constructor
{
count = count + 1;
cout <<"In constructor, object " <<count
<<" is created "<<endl;
}
~sample() //Destructor
{
cout <<"Destructor destroys the object "<< count--
<<endl;
}

}; //End of class sample


void main()
{
cout <<"This is how objects are created and destroyed"<<endl;
sample s1,s2,s3;
}
Class conversions with constructors
• A converting constructor is a single-parameter
constructor that is declared without the function
specifies explicit. The compiler uses converting
constructors to convert objects from the type of
the first parameter to the type of the converting
constructor's class
Example:
#include<iostream.h>
#include<conio.h>
class Y {
int a, b;
char* name;
public:
Y(int i) { cout<<"the value of i is "<<i<<endl;};
Y(const char* n, int j = 0) { cout<<"The value on n and j is "<<n<<j<<endl;};
};
void add(Y) { };
void main() {

clrscr();
Y obj1 = 2;

Y obj2 =Y("somestring",50);
obj1 = 10;
add(Y(5));
getch();
}
• The above example has the following two
converting constructors:
▫ Y(int i)which is used to convert integers to objects
of class Y.
▫ Y(const char* n, int j = 0) which is used to convert
pointers to strings to objects of class Y.
Conversion functions
• A conversion function that belongs to a class X
specifies a conversion from the class type X to
the type specified by the conversion type.
Example:
#include<iostream.h>
#include<conio.h>
class Y {
int b;
public:
void acc()
{
cout<<"enter the value"<<endl;
cin>>b;
}
operator int();
};
Y::operator int()
{
return b;
}
void f(Y obj)
{
int i = int(obj); int j = (int)obj; int k = i + obj;
cout<<"i="<<i<<endl<<"j="<<j<<endl<<"k="<<k<<endl;
}
void main()
{
clrscr();
Y a;
a.acc();
f(a);
getch();
}
Note
• All three statements in function f(Y) use the
conversion function Y::operator int().
• Conversion functions have no arguments, and
the return type is implicitly the conversion type.
• Conversion functions can be inherited.
• You can have virtual conversion functions but
not static ones.
• You cannot use a conversion function to convert
an object of type A to type A, to a base class of A,
or to void.

Das könnte Ihnen auch gefallen