2. CHAPTER CONTENTS
SIMPLE C++ PROGRAM, INPUT OUTPUT STATEMENTS IN C++,
COMPILATION & EXECUTION OF C++ PROGRAM
STRUCTURE OF A C++ PROGRAM
IMPLEMENTATION OF A CLASS, CREATING CLASS OBJECTS,
OPERATIONS ON OBJECTS, RELATIONSHIP AMONG OBJECTS,
ACCESSING CLASS MEMBERS, ACCESS SPECIFIERS,
CONSTRUCTOR AND DESTRUCTOR, TYPES OF CONSTRUCTOR,
STATIC MEMBERS,
EMPTY CLASSES,
NESTED CLASSES,
LOCAL CLASSES,
ABSTRACT CLASSES,
CONTAINER CLASSES.
3. SIMPLE C++ PROGRAM
#include<iostream> // header file
using namespace std;
int main() // main function (the execution begins at main() )
{
cout<<“my first program”; //output statement
return 0; // return statement
}
Note: the C++ statements terminate with semicolon
// single line comments
/* multiple line
comment */
4. HEADER FILES
#include<iostream.h>
# is called Preprocessor directive
Preprocessing is the phase of compilation before
the actual execution.
Header files are the predefined files in the C++
library using which we create new program.
5. NAMESPACE
NAMESPACE:
It is a new concept introduced by ANSI C++ standards
committee.
It defines the scope for the identifiers that are used in a
program.
Here, std is the namespace where ANSI C++ standard
libraries are defined.
This will bring all the identifiers defined in std to the current
global scope.
6. main()
Return type of main()
In C++, main() returns an integer type value to the operating
system.
Therefore, every main in C++ should end with a return
statement; otherwise a warning or an error might occur.
The default return type for all functions in C++ is int.
7. INPUT OUTPUT STATEMENTS
cin >> variable-name;
read the value of the variable called <variable-name> from the user.
The identifier ‘cin’ is a predefined object in C++ that corresponds to the
standard input stream.
The operator >> is known as ‘extraction’ or ‘get from’ operator.
It extracts the value from the keyboard and assigns it to the variable on its
right.
Here the bit-wise right-shift operator is overloaded.
cascading:
cin>>number1>>number2;
The values are assigned from left to right. That is, if we key in two values, say, 10
and 20, then 10 will be assigned to number1 and 20 to number2.
8. INPUT OUTPUT STATEMENTS
cout << variable-name;
prints the value of variable <variable-name> to the user
cout << “any message “;
prints the message within quotes to the user
cout << endl;
prints a new line
The identifier cout is a predefined object that represents the standard
output stream in C++
The operator << is the ‘insertion’ or ‘put to’ operator. It inserts or sends the
contents of the variable on its right to the object on its left.
Here the bit-wise left-shift operator is overloaded.
Cascading:
Cout<<“sum=“<<sum<<“n”<<“average=“<<average<<“n”;
11. SPECIFYING A CLASS
A class is a way to bind the data and its associated
functions together.
A class specification has two parts:
Class declaration
Class function definitions
13. These variables and functions are collectively called
class members.
The variables declared inside the class are known as
data members and functions are known as member
functions.
By default, the members of a class are private.
14. SIMPLE CLASS EXAMPLE
class item
{ int number;
float cost;
public:
void getdata(int a, float b);
void putdata();
};
15. CREATING OBJECTS
classname object_name; //inside main()
Before main()
class item
{
} x,y,z; //at class closing bracket
17. DEFINING MEMBER FUNCTIONS
Member functions can be defined in two places:
Outside the class definition
Inside the class defintion
Irrespective of the place of defintion, the function
performs the same task.
18. OUTSIDE THE CLASS DEFINITION
return-type class-name::function-name(argument)
{
function body
}
:: called the scope resolution operator. The label class-name::
tells the compiler that the function function-name belongs to the
class class-name. That is, it defines the scope of the function.
19. OUTSIDE THE CLASS DEFINITION
For example,
void item:: getdata(int a, float b)
{
number=a;
cost=b;
}
void item:: putdata()
{ cout<<number<<cost;
}
20. INSIDE THE CLASS DEFINITION
For example,
class item
{
int number;
float cost;
public:
void getdata(int a, float b)
{
number=a;
cost=b;
}
void putdata()
{
cout<<number<<“n”<<cost;
}
};
21. COMPLETE PROGRAM
class item
{ int number;
float cost;
public:
void getdata(int a,float b)
{
number=a;
cost=b;
}
void putdata()
{
cout<<number<<cost;
}
};
void item:: getdata(int a, float b)
{ number=a;
cost=b;
}
int main()
{
item x;
x.getdata(100,299.95);
x.putdata();
item y,z;
y.getdata(200,175.50);
z.getdata(300,555.25);
y.putdata();
z.putdata();
return 0;
}
22. PROGRAMS
1. To find sum of two numbers
2. To find greater of two numbers using if else
3. To find greater of two numbers using conditional
operator
4. Find factorial of a number
5. Print multiplication table of a number
6. To find sum of first n natural numbers
7. To find reverse of a number
8. Create simple calculator using switch case
23. MEMORY ALLOCATION FOR OBJECTS
The memory space for objects is allocated when they are
declared and not when the class is specified.
All the objects belonging to class use the same member
functions, no separate space is allocated for member functions
when the objects are created.
Only space for member variables is allocated separately for
each object.
Separate memory locations for the objects are essential,
because the member variables will hold different data values
for different objects.
25. NESTING OF MEMBER FUNCTIONS
A member function can be called by using its name inside another member
function of the same class, known as nesting of member functions.
#include<iostream>
using namespace std;
class set
{ int m,n;
int largest();
public:
void input()
{
cout<<“input the values of m and n”<<“n”;
cin>>m>>n;
}
void display();
//int largest();
};
int set:: largest()
{
if(m>=n)
return m;
else
return n;
}
void set::display()
{
cout<<“largest value=“<<largest()<<“n”;
}
int main()
{
set a;
a.input();
//a.largest();
a.display();
return 0;
}
Output
Input the values of m and n 4
8
Largest value=8
26. STATIC DATA MEMBERS
It is initialized to zero when the first object of its class is
created. No other initialization is permitted.
Only one copy of that member is created for the entire class
and is shared by all the objects of that class, no matter how
many objects are created.
It is visible only within the class, but its lifetime is the entire
program.
These are normally used to maintain values common to the
entire class.
It can be used as a counter that records the occurrences of all
objects.
27. STATIC DATA MEMBERS
The type and scope of each static member variable must be defined outside the
class definition.
Syntax:
datatype classname :: variable;
28. STATIC DATA MEMBERS
#include<iostream>
using namespace std;
class item
{
static int count;
int number;
public:
void getdata(int a)
{
number=a;
count++;
}
void getcount(void)
{
cout<<“count:”;
cout<<count<<“n”;
}
};
int item :: count;
int main()
{
item a,b,c;
a.getcount();
b.getcount();
c.getcount();
a.getdata(100);
b.getdata(200);
c.getdata(300);
cout<<“after reading data”<<“n”;
a.getcount();
b.getcount();
c.getcount();
return 0;
}
29. STATIC MEMBER FUNCTIONS
It can have access to only other static members (functions or
variables) declared in the same class.
It can be called using the class name (instead of its objects) as
follows:
class-name :: function-name;
30. STATIC MEMBER FUNCTIONS
#include<iostream>
using namespace std;
class test
{
static int count;
int code;
public:
void setcode()
{
code=++count;
}
static void showcount()
{
cout<<“count:”<<count<<“n”;
// cout<<code; //error, code is not
//static
}
};
int test :: count;
int main()
{
test t1,t2;
t1.setcode();
t2.setcode();
test:: showcount();
test t3;
t3.setcode();
test:: showcount();
return 0;
}
31. CONSTRUCTORS & DESTRUCTORS
One of the aims of C++ is to create user defined data types
such as class, that behave very similar to the built in types. That
means, we should be able to initialize a class type variable
(object) when it is declared, much the same way as
initialization of an ordinary variable. Similarly, when a
variable of built in type goes out of scope, the compiler
automatically destroys the variable. So constructors and
destructors enable us to initialize the objects when they are
created and destroy them when their presence is no longer
needed.
32. CONSTRUCTOR
Special member function whose task is to initialize the objects
of its class.
It is special because its name is same as the class name.
The constructor is invoked when ever an object of its associated
class is created.
It is called constructor because it constructs the values of data
members of the class.
Should be declared in public section.
It doesn’t have return types, not even void and therefore, it
can’t return values.
It cannot be inherited, though a derived class can call the base
class constructor.
33. USE/NEED OF CONSTRUCTOR
The main use is to initialize objects.
If we don’t initialize a member, then it will take
the garbage value, means uninitialized
member fields have garbage in them. It may
be the cause of serious bugs.
35. DEFAULT CONSTRUCTOR
A constructor with no parameters is called default
constructor.
Also known as ‘no argument’ constructor.
If no constructor is defined, then the compiler
creates a default constructor.
SYNTAX:
class class_name
{
public: class_name() {}
};
36. DEFAULT CONSTRUCTOR
Class rectangle
{
int height;
int width;
public: rectangle()
{
height=6; width=12;
}
void show()
{ cout<<“height=“<<height;
cout<<“width=“<<width;
}
};
int main()
{
rectangle r;
r.show();
}
37. PARAMETERIZED CONSTRUCTOR
The constructor that can take arguments are called
parameterized constructor.
SYNTAX:
class class_name
{
public: class_name(parameter list)
{ }
};
38. PARAMETERIZED CONSTRUCTOR
class rectangle
{
int height; int width;
public: rectangle(int,int);
void show()
{ cout<<“height=“<<height;
cout<<“width=“<<width;
}
};
rectangle::rectangle(int a, int b)
{
height=a; width=b;
}
int main()
{
rectangle r1(10,20);//implicit call
rectangle r2=rectangle(30,40);
//explicit call
r1.show();
r2.show();
}
39. CONSTRUCTOR CALLING
The initial values can be passed in two ways:
EXPLICIT CONSTRUCTOR CALL
IMPLICIT CONSTRUCTOR CALL
40. IMPLICIT CONSTRUCTOR CALL
The constructor is called implicitly i.e. the constructor
is called even when its name has not been
mentioned in the statement.
Shorter and easy to implement.
EXAMPLE:
rectangle r(10,20);
41. EXPLICIT CONSTRUCTOR CALL
The constructor is called explicitly i.e. the name of
the constructor is explicitly provided to invoke it so
that object can be initialized.
EXAMPLE:
rectangle r2=rectangle(30,40);
42. COPY CONSTRUCTOR
Takes reference to an object of the same class as itself as an
argument.
A copy constructor has an object of the class as its only
parameter.
It makes a new object that is duplicate of the original object.
This constructor takes one argument, also called one argument
constructor.
SYNTAX:
class_name obj1(obj2);
or class_name obj1=obj2;
43. COPY CONSTRUCTOR
class A
{
int a;
public: A() {a=1;} //default
A( int w) {a=w;}//parameterized
A (A &i) { a=i.a;}//copy
void show() {cout<<a;}
};
int main()
{
A obj1; //default
A obj2(20);//parameterized
A obj3(obj2); //copy
cout<<“obj1=”<<obj1.show();
cout<<“obj2=“<<obj2.show();
cout<<“obj3=“<<obj3.show();
}
Obj1.a=1
Obj2.a=20
Obj3.a=obj2.a=20
44. OVERLOADED CONSTRUCTOR
Although a constructor is a special member function,
it is still considered a function and like all functions
in C++, can be overloaded.
Differentiated on the basis of different data types
or number of parameters.
45. OVERLOADED CONSTRUCTOR
class Myclass
{
public: int x, int y;
Myclass()
{ x=0; y=0; }
Myclass(int i)
{ x=y=i; }
Myclass(int i, int j)
{ x=i; y=j;}
};
int main()
{
Myclass t; //default
Myclass t1(5); //
Myclass t2(9,10);//
cout<<t.x<<t.y;
cout<<t1.x<<t1.y;
cout<<t2.x<<t2.y;
}
46. DYNAMIC CONSTRUCTOR
The constructor can also be used to allocate
memory while creating objects.
The data members of an object can be initialized at
run time using constructors. This is known as dynamic
initialization.
Done with the help of ‘new’ and ‘delete’ operators.
Memory allocation done with ‘new’ operator and
the allocated memory can be released with the
help of ‘delete’ operator.
47. DYNAMIC CONSTRUCTOR
class A
{
int *p;
public:
A()
{ p=new int;
*p=100;
}
A(int v)
{
p=new int;
*p=v;
}
int display()
{
return (*p);
}
};
int main()
{
A obj1,obj2(90);
cout<<obj1.display();
cout<<obj2.display();
}
48. DESTRUCTOR
Inverse of constructor functions
Used to destroy the objects that have been created
by a constructor
Member function whose name is the same as the class
name and is preceded by a tilde (~)
Invoked upon exit from block or function or program
Never takes any argument nor does it return any
value
Used to clean up storage that is no longer accessible
50. DESTRUCTOR
class HelloWorld
{
public:
HelloWorld()
{ cout<<"Constructor is called"<<endl; }
~HelloWorld()
{ cout<<"Destructor is called"<<endl; }
void display()
{ cout<<"Hello World!"<<endl; }
};
int main()
{ HelloWorld obj;
obj.display();
return 0; }
OUTPUT
Constructor is called
Hello World!
Destructor is called
51. DESTRUCTOR
int count=0;
class alpha
{
public:
alpha()
{
cout<<“nconstructor”;
count++;
cout<<“ncount=“<<count;
}
~alpha()
{
cout<<“ndestructor”;
count--;
cout<<“ncount=”;<<count
;
}
};
int main()
{
cout<<“enter main”;
alpha A1, A2, A3, A4;
{ cout<<“nenter block1”;
alpha A5;
}//destructor for A5
{
cout<<“enter block2”;
alpha A6;
} //destructor for A6
cout<<“re enter main”;
return 0;
} //ending block for main
(A1 A2 A3 A4)
A4 A3 A2A1
Enter main
Constructor
Count=1
Constructor
Count=2
Constructor
Count=3
Constructor
Count=4
Enter block1
Constructor
Count=5
Destructor
Count=4
Enter block2
Constructor
Count=5
Destructor
Count=4
Re enter main
Destructor
Count=3
Destructor
Count=2
Destructor
Count=1
Destructor
52. EMPTY CLASSES
#include<iostream>
class no_members
{
};
int main()
{ no_members n;
}
The memory allocated for such objects is of non-zero size.
Therefore, the objects have different addresses.
Having different addresses makes it possible to compare
pointers to objects for identity.
Can be used in template programming.
It requires empty classes to have non-zero size to ensure object
identity.
53. NESTED CLASSES
The provision for embedding one class within another would
further enhance the power of data abstraction thereby
enabling the programmers to construct powerful data
structures.
If a class A and another class B is defined within the scope of
A, then A is called the host class or outer class or qualifier class
and B is called nested class or inner class.
An object of class A can be declared as usual by using the
data type A. But to declare the objects of B class, we should
use A::B as the data type.
54. NESTED CLASSES
class alpha
{
public: int a;
alpha(int i=0)
{ a=i;}
void display()
{cout<<“a=“<<a;}
class beta
{
public: int b;
beta(int j=0)
{ b=j;}
void show()
{ cout<<“nb=“<<b;}};
};
int main()
{
alpha a1(10);
a1.display();
alpha::beta m(20);
m.show();
}
OUTPUT:
a=10
b=20
55. LOCAL CLASSES
The C++ language also supports defining classes within the body of
functions. Such classes are called local classes. The local classes have scope
only within their enclosing functions i.e. the objects of these classes may be
declared only within the body of the functions.
SYNTAX:
class A { };
type function (arguments)
{ class B { }; //local class
B b;
}
56. LOCAL CLASSES
class alpha
{ int a;
public: void get()
{ cout<<“enter the value of a”;
cin>>a;
}
void display()
{
cout<<“na=“<<a;
}
};
int main() {
class beta
{ int b;
public: void get()
{ cout<<“enter the value of b”;
cin>>b;
}
void display()
{ cout<<“nb=“<<b; }
};
alpha a1;
a1.get();
a1.display();
beta m;
m.get();
m.display();
}
OUTPUT:
enter the value of a10
a=10
enter the value of b20
b=20
57. LOCAL CLASSES
void f()
{
class test
{
public: void method()
{
cout<<“local class method”;
}
};
test t;
t.method();
}
int main()
{
f();
return 0;
}
58. ABSTRACT CLASSES
Abstract class is a class which contains atleast one pure virtual
function in it.
These are used to provide an interface for its sub classes.
Classes inheriting the abstract class must provide definition to
the pure virtual function, otherwise they will also become
abstract class.
Can have normal functions and variables along with pure
virtual function.
All the virtual functions must be implemented in the derived
class, or else they will become derived class.
59. PURE VIRTUAL FUNCTION
A virtual function with no definition is known as pure
virtual function.
Start with keyword ‘virtual’ and end with ‘=0’.
For example,
virtual void f()=0;
60. PROGRAM FOR ABSTRACT CLASS
class base
{
public: virtual void show()=0;
};
class derived : public base
{
public: void show()
{
cout<<“virtual function in derived class”;
}
};
int main()
{
base obj; //compile time error
base *b;
derived d;
b=&d;
bshow();
}
OUTPUT:
virtual function in derived class
61. CONTAINER CLASSES
A container is a holder object that stores a collection of other objects (its
elements).
These are ‘Sequence Containers’ and ‘Associative Containers’.
Sequence containers: Being templates, they can be used to store arbitrary
elements. One common property of all sequential containers is that the
elements can be accessed sequentially. Like all other standard library
components, they reside in namespace std.
Associative containers: refer to a group of class templates in the standard
library that implement ordered associative arrays. Being templates, they
can be used to store arbitrary elements. The following containers are
defined in the current revision of the C++ standard: set, map, multiset,
multimap.
62. SEQUENCE CONTAINERS
The following containers are defined in the current revision of
the C++ standard: array, vector, list, forward_list, deque. Each
of these containers implements different algorithms for data
storage, which means that they have different speed
guarantees for different operations:
array implements a compile-time non-resizable array.
vector implements an array with fast random access and an
ability to automatically resize when appending elements.
deque implements a double-ended queue with comparatively
fast random access.
list implements a doubly linked list.
forward_list implements a singly linked list.
63. ASSOCIATIVE CONTAINERS
The associative containers can be grouped into two subsets:
maps and sets.
A map, sometimes referred to as a dictionary, consists of a
key/value pair. The key is used to order the sequence, and the
value is somehow associated with that key.
A set is simply an ascending container of unique elements.