Sei sulla pagina 1di 30

SRI RAMAKRISHNA

INSTITUTE OF TECHNOLOGY

Programming and Data


Structures - II
UNIT – I
C++ Programming features - Data Abstraction - Encapsulation - class - object - constructors - static
members – constant members – member functions – pointers – references - Role of this pointer
– Storage classes – function as arguments.

10/10/2020 R.Nagendran 1
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Example : A simple C++ program – To display “Hello World”

#include <iostream.h>
using namespace std;
// main() is where program execution begins.
void main()
{
cout << "Hello World"; // prints Hello World

10/10/2020 R.Nagendran 2
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Class, Objects, Data members, Member functions

Syntax
Class classname
{
Data members;
Data functions();
Public:
Data members;
Data functions();
};
10/10/2020 R.Nagendran 3
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY

• Object - Objects have states and behaviors. Example: A Student has states -
color, name, as well as behaviors - reading, writing, eating. An object is an
instance of a class.
• Class - A class can be defined as a template/blueprint that describes the
behaviors/states that object of its type support.
• Methods/Member functions - A method is basically a behavior. A class can
contain many methods. It is in methods where the logics are written, data is
manipulated and all the actions are executed.
• Instance Variables/Data Members - Each object has its unique set of
instance variables. An object's state is created by the values assigned to these
instance variables.
10/10/2020 R.Nagendran 4
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Class SecondIT
{
int regno;
char name[20];
public :
void getdata();
void putdata();
};

10/10/2020 R.Nagendran 5
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
class secondIT main()
{
{
int regno; secondIT arun, ashwin, mithra,saraswathi;
char name[20]; arun.getdata();
ashwin.getdata();
public :
mithra.getdata();
void getdata() saraswathi.getdata();
{ arun.putdata();
ashwin.putdata();
cin>>regno;
mithra.putdata();
cin>>name; saraswathi.putdata();
} }
void putdata()
{
cout<<regno;
cout<<name;
} }

}; 10/10/2020 R.Nagendran 6
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
•Accessing the Data Members: //box 2 specification
#include <iostream> Box2.height = 10.0;
using namespace std; Box2.length = 12.0;
class Box Box2.breadth = 13.0;
{
public: double length; // Length of a box
// volume of box 1
double breadth; // Breadth of a box
double height; // Height of a box
volume = Box1.height * Box1.length *
Box1.breadth; cout << "Volume of Box1 : " <<
};
volume <<endl;
int main( )
{
Box Box1; // Declare Box1 of type Box // volume of box 2
Box Box2; // Declare Box2 of type Box volume = Box2.height * Box2.length *
double volume = 0.0; // Store the volume of a box here Box2.breadth; cout << "Volume of Box2 : " <<
// box 1 specification volume <<endl;
Box1.height = 5.0; return 0;
Box1.length = 6.0; }
Box1.breadth
10/10/2020 = 7.0; R.Nagendran 7
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
#include <iostream> // Main function for the program
using namespace std; int main( )
class Box {
{ Box Box1; // Declare Box1 of type Box
public: Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store
double length; // Length of a box the volume of a box here
double breadth; // Breadth of a box // box 1 specification
double height; // Height of a box Box1.setLength(6.0);
// Member functions declaration Box1.setBreadth(7.0);
double getVolume(void); Box1.setHeight(5.0);
void setLength( double len ); // box 2 specification
void setBreadth( double bre ); Box2.setLength(12.0);
void setHeight( double hei ); Box2.setBreadth(13.0);
}; Box2.setHeight(10.0);
// volume of box 1
// Member functions definitions
volume = Box1.getVolume();
double Box::getVolume(void)
cout << "Volume of Box1 : " << volume <<endl;
{ return length * breadth * height; } // volume of box 2
void Box::setLength( double len ) volume = Box2.getVolume();
{ length = len; } cout << "Volume of Box2 : " << volume <<endl;
void Box::setBreadth( double bre ) { breadth = bre; } return 0;
void Box::setHeight( double hei ) { height = hei; } }
10/10/2020 R.Nagendran 8
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
• C++ Class access modifiers
• class Base
{
private: // private members go here
protected: // protected members go here
public: // public members go here
};
• Default Private.

10/10/2020 R.Nagendran 9
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
The Class Constructor: • A constructor will have exact same
• A class constructor is a special name as the class and it does not have
member function of a class that is any return type at all, not even void.
executed whenever we create new Constructors can be very useful for
objects of that class. setting initial values for certain
member variables.

10/10/2020 R.Nagendran 10
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
void Line::setLength( double len )
#include <iostream> {
length = len;
using namespace std; }
class Line double Line::getLength( void )
{ {
public: return length;
void setLength( double len );
double getLength( void ); }
Line(); // This is the constructor
// Main function for the program
private: int main( )
double length; {
}; Line line;
// Member functions definitions including constructor // set line length
line.setLength(6.0);
Line::Line(void)
{ cout << "Length of line : " << line.getLength() <<endl;
cout << "Object is being created" << endl;
} return 0;
}
10/10/2020 R.Nagendran 11
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Parameterized Constructor: double Line::getLength( void )
#include <iostream> { return length;}
using namespace std;
class Line
{ // Main function for the program
public: int main( )
void setLength( double len ); { Line line(10.0);
double getLength( void );
Line(double len);
// get initially set length.
// This is the constructor cout << "Length of line : " << line.getLength() <<endl;
private: double length; // set line length again line.setLength(6.0);
}; cout << "Length of line : " << line.getLength() <<endl;
// Member functions definitions including constructor
return 0;
Line::Line( double len)
{ }
cout << "Object is being created, length = " << len << endl;
length = len; OUTPUT:
Object is being created, length = 10
}
Length of line : 10
void Line::setLength( double len ) Length of line : 6
{ length = len;}
10/10/2020 R.Nagendran 12
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
• The Class Destructor:
• A destructor is a special member function of a class that is executed whenever
an object of it's class goes out of scope or whenever the delete expression is
applied to a pointer to the object of that class.
• A destructor will have exact same name as the class prefixed with a tilde (~) and
it can neither return a value nor can it take any parameters. Destructor can be
very useful for releasing resources before coming out of the program like closing
files, releasing memories etc.

10/10/2020 R.Nagendran 13
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
#include <iostream>
void Line::setLength( double len )
using namespace std;
class Line { length = len;}
{ double Line::getLength( void )
public: { return length;}
void setLength( double len ); // Main function for the program
double getLength( void );
Line();
int main( )
// This is the constructor declaration {
~Line(); Line line;
// This is the destructor: declaration // set line length
private: line.setLength(6.0);
double length;
};
cout << "Length of line : " << line.getLength() <<endl;
// Member functions definitions including constructor return 0;
Line::Line(void) }
{ cout << "Object is being created" << endl; OUTPUT:
} Object is being created
Line::~Line(void)
{ Length of line : 6
cout << "Object is being deleted" << endl; Object is being deleted
}
10/10/2020 R.Nagendran 14
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
• STATIC MEMBER: • A static member is shared by all
• We can define class members static objects of the class. All static data is
using static keyword. When we initialized to zero when the first
declare a member of a class as static it object is created, if no other
means no matter how many objects of initialization is present. We can't put it
the class are created, there is only one in the class definition but it can be
copy of the static member. initialized outside the class as done in
the following example by redeclaring
the static variable, using the scope
resolution operator :: to identify
which class it belongs to.

10/10/2020 R.Nagendran 15
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
#include <iostream> private:
double length; // Length of a box
using namespace std; double breadth; // Breadth of a box double
class Box height; // Height of a box
{ };
public: // Initialize static member of class Box
int Box::objectCount = 0;
static int objectCount;
// Constructor definition int main(void)
Box(double l=2.0, double b=2.0, double h=2.0) {
Box Box1(3.3, 1.2, 1.5); // Declare box1
{ Box Box2(8.5, 6.0, 2.0); // Declare box2
cout <<"Constructor called." << endl; // Print total number of objects.
length = l; cout << "Total objects: " << Box::objectCount << endl;
breadth = b; return 0;
}
height = h;
// Increase every time object is created OUTPUT:
objectCount++; Constructor called.
} Constructor called.
double Volume() Total objects: 2
10/10/2020 R.Nagendran 16
{ return length * breadth * height; }
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Static Member Function : • Static member functions have a class
• By declaring a function member as scope and they do not have access to
static, you make it independent of any the this pointer of the class. You could
particular object of the class. A static use a static member function to
member function can be called even if determine whether some objects of the
no objects of the class exist and the class have been created or not.
static functions are accessed using
only the class name and the scope
resolution operator ::.
• A static member function can only
access static data member, other static
member functions and any other
functions
10/10/2020 from outside the class. R.Nagendran 17
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
#include <iostream> static int getCount()
using namespace std; { return objectCount; }
class Box private: double length; // Length of a box
double breadth; // Breadth of a box
{ double height; // Height of a box
public: };
static int objectCount; // Initialize static member of class
Boxint Box::objectCount = 0;
// Constructor definition int main(void)
Box(double l=2.0, double b=2.0, double h=2.0) {
{ cout <<"Constructor called." << endl; // Print total number of objects before creating object.
cout << "Inital Stage Count: " << Box::getCount() << endl;
length = l; Box Box1(3.3, 1.2, 1.5); // Declare box1
breadth = b; Box Box2(8.5, 6.0, 2.0); // Declare box2
height = h; // Print total number of objects after creating object.
cout << "Final Stage Count: " << Box::getCount() << endl;
// Increase every time object is created return 0;
objectCount++; }
} OUTPUT:
Inital Stage Count: 0
double Volume() Constructor called.
{ return length * breadth * height; } Constructor called.
R.Nagendran
10/10/2020 Final Stage Count: 2 18
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
• STORAGE CLASSES:
 
• A storage class defines the scope (visibility) and life-time of variables
and/or functions within a C++ Program. These specifiers precede the type
that they modify. There are following storage classes, which can be used in
a C++ Program
• auto
• register
• static
• extern
10/10/2020 R.Nagendran 19
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
C++ POINTERS: #include <iostream>
using namespace std;
• C++ pointers are easy and fun to learn. int main ()
Some C++ tasks are performed more easily
with pointers, and other C++ tasks, such as { int var1;
dynamic memory allocation, cannot be char var2[10];
performed without them. cout << "Address of var1 variable: ";
• As you know every variable is a memory cout << &var1 << endl;
location and every memory location has its cout << "Address of var2 variable: ";
address defined which can be accessed
using ampersand (&) operator which cout << &var2 << endl;
denotes an address in memory. return 0;
}
OUTPUT:
10/10/2020 Address of var1 variable: 0xbfebd5c0
R.Nagendran 20
Address of var2 variable: 0xbfebd5b6
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
A pointer is a variable whose value is the #include <iostream>
address of another variable. Like any variable using namespace std;
or constant, you must declare a pointer before int main ()
{ int var = 20; // actual variable declaration.
you can work with it. The general form of a
int *ip; // pointer variable
pointer variable declaration is: ip = &var; // store address of var in pointer variable
cout << "Value of var variable: ";
type *var-name; cout << var << endl;
// print the address stored in ip pointer variable
Example: cout << "Address stored in ip variable: ";
int *ip; // pointer to an integer cout << ip << endl; // access the value at the address available in
double *dp; // pointer to a double pointer
float *fp; // pointer to a float cout << "Value of *ip variable: "; cout << *ip << endl;
return 0;
char *ch // pointer to character
}
OUTPUT:
Value of var variable: 20
Address stored in ip variable: 0xbfc601ac
10/10/2020 ValueR.Nagendran
of *ip variable: 20 21
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Pointers and arrays OUTPUT
Enter 5 Numbers
main() 11
{ 22
33
int x[10], I; 44
clrscr(); 55
cout<< “Enter 5 Numbers \n”; You have Entered
At Address 0x8faffe2 the value is 11.
for(i=0;i<5;i++) At Address 0x8faffe4 the value is 22.
cin>>x[i]; At Address 0x8faffe6 the value is 33.
At Address 0x8faffe8 the value is 44.
cout<< “\n You have Entered”;
At Address 0x8faffe10 the value is 55.
for(i=0;i<5;i++)
11 22 33 44 55
cout<<“\n At Address” << (x+i) << “ the value is
“<<*(x=i);
}

x[0] x[1] x[2] x[3] x[4]


10/10/2020 R.Nagendran 22
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Pointer Arithmetic
cout<<“\n Accessing elements(k++):”<<*k;
k++;
cout<<“\n Accessing elements(k++):”<<*k;
# define size 10 k--;
main() cout<<“\n Accessing elements(k--):”<<*k;
k=k+3;
{ cout<<“\n Accessing elements(k+2):”<<*k;
int x [size],n;
}
int *k;
clrscr(); OUTPUT
Enter number of elements in an array
cout<< “\n Enter number of elements in an array”; 5
cin>>n; Enter the elements in an array : 10 20 30 40 50
Accessing elements(base address)
cout<<“\n Enter the elements in an array\n”; 10
for(i=0;i<n; i++) Accessing elements(k++)
20
{ Accessing elements(k++)
cin>> x[i]; 30
k=&x[0]; Accessing elements(k--)
20
cout<<“\n Accessing elements(base address):”<<*k; Accessing elements(k+2)
k++; 50

10/10/2020 R.Nagendran 23
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY

1.00 2.00 3.00 4.00 5.00


m i t a \0

100 101 102 103 104


• 100 104 108 112 116

111 2 3 4 5

100 102 104 106 108

10/10/2020 R.Nagendran 24
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Function as Argument
void myfunc(int x)
{
cout<<“\n Value from argument function is “<< x;
}
main()
{
void(*testFun(int);
testFun = &myfunc;
testFun(10);
}
10/10/2020 R.Nagendran 25
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
Pointer to Object
class test void main()
{ {
private: test obj(100),*ptr_obj;
int a;
ptr_obj = &obj;
public:
test(int b) cout<<“Value of pointer object :”;
{ cout<<ptr_obj ->getval();
a=b; }
}
int getval()
OUTPUT :
{
return a;
} 100
};
10/10/2020 R.Nagendran 26
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
• C++ References
• A reference variable is an alias, that is, another name for • Creating References in C++:
an already existing variable. Once a reference is initialized • Think of a variable name as a label attached to the
with a variable, either the variable name or the reference variable's location in memory. You can then think of a
name may be used to refer to the variable. reference as a second label attached to that memory
• C++ References vs Pointers: location. Therefore, you can access the contents of the
variable through either the original variable name or the
• References are often confused with pointers but three reference. For example, suppose we have the following
major differences between references and pointers are: example:
• You cannot have NULL references. You must always be • Int i=17
able to assume that a reference is connected to a • We can declare reference variables for i as follows.
legitimate piece of storage.
• int& r=i;
• Once a reference is initialized to an object, it cannot be
changed to refer to another object. Pointers can be • Read the & in these declarations as reference. Thus, read
pointed to another object at any time. the first declaration as "r is an integer reference initialized
to i" and read the second declaration as "s is a double
• A reference must be initialized when it is created. Pointers reference initialized to d.". Following example makes use of
can be initialized at any time. references on int and double:

10/10/2020 R.Nagendran 27
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
#include <iostream> When the above code is compiled together and
executed, it produces the following result:
using namespace std;
OUTPUT
int main ()
{ Value of i : 5
// declare simple variables Value of i reference : 5
int i;
double d; Value of d : 11.7
// declare reference variables Value of d reference : 11.7
int& r = i;
double& s = d;

i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;

d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
10/10/2020 R.Nagendran 28
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY

• this Pointer
• Every object in C++ has access to its own address through an
important pointer called this pointer. The this pointer is an implicit
parameter to all member functions. Therefore, inside a member
function, this may be used to refer to the invoking object.
• Friend functions do not have a this pointer, because friends are not
members of a class. Only member functions have a this pointer.
• The following example to understand the concept of this pointer:

10/10/2020 R.Nagendran 29
SRI RAMAKRISHNA
INSTITUTE OF TECHNOLOGY
#include <iostream> int compare(Box box)
{
using namespace std; return this->Volume() > box.Volume();
  }
class Box private:
{ double length; // Length of a box
double breadth; // Breadth of a box
public: double height; // Height of a box
// Constructor definition };
Box(double l=2.0, double b=2.0, double h=2.0)  
{ int main(void)
cout <<"Constructor called." << endl; {
length = l; Box Box1(3.3, 1.2, 1.5); // Declare box1
breadth = b; Box Box2(8.5, 6.0, 2.0); // Declare box2
 
height = h; if(Box1.compare(Box2))
} {
double Volume() cout << "Box2 is smaller than Box1" <<endl;
}
{ else
{
return length * breadth * height; cout << "Box2 is equal to or larger than Box1" <<endl;
}
} 10/10/2020 R.Nagendran
return 0; 30

Potrebbero piacerti anche