Vous êtes sur la page 1sur 67

C++

CDAC MUMBAI

BASIC INPUT/OUTPUT

C++ uses a convenient abstraction called streams to


perform input and output operations in sequential
media such as the screen or the keyboard. A stream is
an object where a program can either insert or extract
characters to/from it.
The standard C++ library includes the header file
iostream, where the standard input and output stream
objects are declared.

STANDARD OUTPUT (COUT).

By default, the standard output of a program is the


Monitor screen.
cout is the standard output stream in C++. It is a
predefined object.

cout is used in conjunction with the insertion operator.

The operator << is called insertion or put to operator.

It inserts (or sends) the contents of the variable on its


right to the object on its left.

cout << "Output sentence";


// prints Output sentence on screen
cout << 120; // prints number 120 on screen
cout << x; // prints the content of x on screen

OUTPUT OPERATOR
Screen
.
..

cout

<<

C++

Object

Insertion
operator

Variable

STANDARD INPUT (CIN).


The standard input device is usually the
keyboard. Handling the standard input in
C++ is done by applying the overloaded
operator of extraction (>>) on the cin stream.
cin is a predefined object in C++ that
corresponds to the standard input stream.
The >> is known as extraction or get from
operator.
It extracts or takes the value from the keyboard
and assigns it to the variable on its right.

INPUT OPERATOR

Eg cin >> number;


Object

Extraction
operator

Cin

>>

------Keyboard

Variable
(number)

45.4

SCOPE RESOLUTION OPERATOR ( :: )


Unary scope resolution operator
Hidden

global variables can be accessed


Hidden local variables cannot be accessed
int a=10;
void main ()
{
int a=20;
{
int a=30;
cout<<local a=<< a;
cout<<hidden global a=<< ::a;
}
cout<<hidden local a=<<a;
}

//30
//10;
//20;

NAMESPACE

Defines a scope that could hold global identifier


that are used in a program.
For using the identifiers defined in the
namespace scope we must include the using
directive, like
using namespace std
std is the namespace where ANSI C++ standard
class libraries are defined

DEFINING A NAMESPACE
namespace namespace_name
{
// Declarations of Variables,
// Functions ,Classes etc.
}
Example:
namespace Mynamespace
{
int m;
void display(int n)
{
cout<<n;
}
}
// no semicolon here
To access identifiers declared within namespace, we use scope resolution
operator (::) shown below
Mynamespace::m=100
Mynamespace::display(10);

USING NAMESPACE

If members of a namespace are frequently used, the


above approach becomes cumbersome.
We can use a using directive to simplify their access
using following two ways.
using namespace namespace_name // using directive
using namespace_name::member_name // using declaration

Ex: using namespace Mynamespace;


m=100;
//Ok
display(200);
//Ok
using Mynamespace::m
m=100;
//Ok
display(200);
//Not Ok display not visible

CLASSES

CLASS & OBJECT

Object:
An Object is a combination of data and behavior.
Object behavior is referred using terms such as
functions, member functions, methods or operations.
Data characterizes the state of an object.
Class:
Description of common properties of objects that
belong to the class i.e., collection of objects with
common characteristics.
A class does not exist in the memory of computer
during program execution.
e.g.: Writing material is a class. Pen and Pencil
are objects of the class.

CLASS

A class is an expanded concept of a data structure:


instead of holding only data, it can hold both data and
functions.
An object is an instantiation of a class. In terms of
variables, a class would be the type, and an object
would be the variable of that type.
Class is a logical abstraction, but an object has physical
existence.
Classes are generally declared using the keyword class,
with the following format:
class class_name
{
access_modifier_1:
//private by default
member variables;
access_modifier_2:
member functions;
...
} object_names;

ATTRIBUTES OF CLASS
Member variables:

State or properties of an object of that class.


Various variables that are defined in the class
They are attributes of an object.

Member functions:

They are actions that object can do.


Used to access data inside the class.
They are handles to the outside world and other objects.

Constructors
Destructors
Static functions
Non-static
Const functions
Virtual functions

- memory allocation, initialization of data


- freeing the memory
- class oriented, modify only static data
- object oriented
- cannot modify data members values
- help dynamic binding of function calls

ACCESS MODIFIERS
Members can be declared
Private
visible only inside the class
Protected
private + visible to the immediately derived class
Public
globally visible

CLASS DECLARATION

A simple class example


class item
{
int number; // variable declaration
float cost;
// private by default
public:
void getdata(int a,float b); // functions declarations
void putdata(void);
// using prototype
};

CREATING OBJECTS
Once a class has been declared, we can create
variables of that type by using the class name.
Eg:

item x;
Item x, y, z;

//memory for x is created.


// memory for x ,y and z are created.

Objects can also be created when a class is defined


by placing their names immediately after the
closing braces.
Eg:

class item
{ ..
}x,y,z;

ACCESSING CLASS MEMBERS


The private data of a class can be accessed only
through the member function of that class.
The general form is

object-name.function-name(actual-arguments);

for eg, the function call statement


x.getdata(100,75.5);
is valid and assigns the value 100 to number
and 75.5 to cost of object x by implementing
getdata() function.
x.number = 100; is invalid statement.

CLASSES
Object is an instance of a class, and the process
of creating an object is called instantiation.
Function declared within the definition of a
class is called a member function or method.
Member function can be defined in two places:

1. Outside the class definition


2. Inside the class definition

CLASSES
Irrespective of the place of definition, the
function should perform the same task.
The code in both the case remains the
same, however the difference is the
function header defined.
1. Outside the class definition

member

function that are declared inside a


class have to be defined separately outside the
class.

The

general form of a member function


definition is

OUTSIDE THE CLASS DEFINITION


return-type class-name :: function -name ( argument declaration)
{
function-body
}

Eg : member function for getdata()


void item :: getdata(int a,float b)
{
number = a;
const = b; }

AN EXAMPLE WITH CLASS


#include <iostream.h>
class person
{
char name[30];
int age;
public:
void getdata(void);
void display(void);

//new data type

};

void person :: getdata(void) // member function


{
cout << Enter name:
cin >> name;
cout << enter age ;
cin >> age;
}

AN EXAMPLE WITH CLASS


void person :: display(void) //member function
{
cout <<\n name : << name;
cout << \n age: <<age;
}
main(void)
{
person p;
//object of type person
p.getdata();
p.display();
}

INSIDE THE CLASS DEFINITION


Another
method of defining a member
function is to replace the function declaration by
the function definition inside the class.
When a function is defined inside a class, it is
treated as an inline function.
Normally small function are defined inside the
class definition.
If a member function is implemented outside
the class braces, it is not inline by default, but it
can be defined as inline using the inline
keyword.

INLINE FUNCTIONS

Eliminates the function-call overhead


(caused by jumping in and out of functions
having few statements) involved in the
conventional functioning approach.
Keyword inline before function
Asks the compiler to copy code into
program instead of making function call
Good for small, often-used functions
inline ReturnType FunctionName(Parameters)
{
// Body of a function
}

INSIDE THE CLASS DEFINITION


class item
{
int number ;
float cost ;
public:
void getdata(int a,float b); //declaration
//inline function

void putdata(void) //definition


{
cout<< number<<endl <<cost<<\n;
}

};

NESTING OF MEMBER FUNCTIONS


A member function of a class can be called only by
an object of that class using a dot operator.
A member function can be called using its name
inside another member function of the same class.
This is known as nesting member function.

#include <iostream.h>
class set
{
private:
int m , n;
public :
void input(void);
void display(void);
int largest(void);
};

NESTING OF MEMBER FUNCTIONS


int set :: largest(void)
{
if(m>= n)
return(m);
else
return(n);
}
void set::display(void)
{
cout <<largest value = <<largest()<<\n;
//calling member function
}

main(void)
{
set A;
A.input();
A.display();
}

MEMORY ALLOCATION FOR OBJECTS

Memory space for objects is allocated when


they are declared and not when the class is
specified.
The member functions are created and placed
in the memory space only once when they are
defined as a part of class specification.
Separate memory locations for the objects are
essential because the member variables will
different data values for different objects.

MEMORY ALLOCATION FOR OBJECTS


common for all objects
member function1
member function2
object1

member variable1
member variable2

object2

member variable2
member variable2

object3

member variable3
member variable2

STATIC DATA MEMBERS


A data member of a class can be declared static;
it can be either in the public or private part of
the class definition.
Static members are members that are single
shared member common to all the objects
created for a particular class.
Memory allocation is done only once and not
every time an object is created.
Such a data member is created and initialized
only once, in contrast to non-static data
members, which are created again and again,
for each separate object of the class.
A static data member is created once, when the
program starts executing.

STATIC DATA MEMBERS


#include<iostream.h>
class shared {
static int a;
int b;
public:
void set(int i, int j) {a=i;b=j;}
void show();
};
int shared::a;
void shared::show()
{
cout<<"This is static a: "<<a;
cout<<"\nThis is non-static b: "<<b;
cout<<"\n";
}

STATIC DATA MEMBERS


int main()
{
shared x,y;
x.set(1,1);

x.show();
y.set(2,2);
y.show();
x.show();
return 0;
}
Note that the type and scope of each static
member variable must be defined outside the
class definition.

SHARING OF A STATIC DATA MEMBER


Object 1
x

Object 2
y

2
a
Common to two objects

STATIC MEMBER FUNCTION

A static functions can have access to only


other static members (functions or
variables) declared in the same class.
A static member function can be called
using the class name
Functions which are static and which are
declared in the public section of a class
interface can be called without specifying
an object of the class.

STATIC MEMBER FUNCTION


#include<iostream.h>
class test
{
int no;
static int count ; // static member variable
public:
void setno(void)
{
no=++count;
}
void showno(void)
{
cout <<number<<no<<endl; }
static void showcount( )
{
cout<<endl<<count; }
};

STATIC MEMBER FUNCTION


int test :: count;
void main ( )
{
test t1,t2;
t1.setno();
t2.setno();
test::showcount();
test t3;
t3::setno();
test::showcount();
t1::showno();
t2::showno();
t3::showno();

ARRAY OF OBJECTS
Consider class definition :
class employee
{
char name [30];
float age;
public:
void getdata(void);
void putdata(void);
};
The identifier employee is a user-defined data
type and can be used to create objects that relate
different categories of the employees.

ARRAY OF OBJECTS
employee manager[3];
employee clerk[23];

// array of manager
// array of clerk

The array manager contains


3 objects
(managers) , namely manager[0], manager[1] and
manager[2] , of type employee class.
The clerk array contains 23 objects(clerks) of
type employee.
The statement manager[ i ] .putdata( ); will
display the data of the i th element of the array
manager.

ARRAY OF OBJECTS
name
age
name

Manager[0]

Manager[1]

age
name
age

Manager[2]

CONSTANT DATA MEMBER AND


CONSTANT FUNCTIONS
A

constant variable can be declared using const


keyword
The const keyword specifies that a variable's
value is constant and tells the compiler to
prevent the programmer from modifying it.
Compiler error results if attempted to modify it
Syntax:
const <variable-name> = <value>
Example:
const int age = 20;
const int age;
// Not valid

CONSTANT DATA MEMBER AND


CONSTANT FUNCTIONS

Declaring a member function with the const


keyword specifies that the function is a "readonly" function that does not modify the object for
which it is called.
If a const function attempt to change the data,
the compiler will generate an error message.
Illegal to declare a const member function that
modifies a data member

CONSTANT DATA MEMBER AND CONSTANT


FUNCTIONS
class Time
{
int hour;
public:
Time(int k) { hour=k;
}
void update( ) { hour++;
}
int value( ) const { return hour; }
void cheat( ) const { hour++;
}
// error this is const
};
void main (void)
{
Time t(10);
cout<<t.value( );
// 11
}

Constructors, Destructors

CONSTRUCTORS AND DESTRUCTORS

A class in C++ contain two special categories of


member functions which are involved in the
internal workings of the class.
These member function categories are,
1. The constructors
2. The destructor

CONSTRUCTOR
Constructors are special member functions
with the same name as the class.
A constructor initializes each object when it
is created
They are commonly used to initialize the
member variables, without the need to make
a separate call to a member function.

The constructor is a member function that is


executed automatically whenever an object is
created.
They should be declared in public section.

CONSTRUCTOR CONTD..

The constructor has no return type, since the


constructor is called automatically when an
object is created.
A constructor is called whenever an object is
defined or dynamically allocated using the new
operator
If no constructor is explicitly written then a
default is created (not in the case of const and
reference data members).
Like other C++ functions, they can have default
arguments.
A constructor that accepts no parameters are
called the default constructor.
The default
constructor for class A is A :: A().

TYPES OF CONSTRUCTORS

Default constructor
Parameterized constructors
Default argument constructors
Copy Constructors
Dynamic Constructors

DEFAULT & PARAMETERIZED CONSTRUCTOR


#include<iostream>
class integer
{
private :
int I ;
public :
void getdata( )
{
cout << endl << Enter any integer ;
cin>>i;
}
void setdata(int j)
{
i =j;
}
integer() // zero argument or Default constructor
{
}
integer(int j) // overloaded or parameterized constructor
{
i=j;
};
void displaydata() {
cout <<endl<<value of i = << i; }
};

DEFAULT & PARAMETERIZED CONSTRUCTOR

void main()
{
integer i1(100),i2,i3;

// Constructor called implicitly

// integer i1 = integer(100); //constructor called implicitly

i1.displaydata( );
i2.setdata(200);
i2.displaydata();
i3.getdata( );
/*300 is entered as I/p */
i3.displaydata( );
}

CONSTRUCTORS WITH DEFAULT ARGUMENTS


class sum
{
int x, y;
public:
sum(int i, int j=10);
void displaydata() {
cout <<value of x = << x<<endl;
cout <<value of y = << y<<endl; }
};
sum::sum(int i,int j)
{x=i;y=j;}
void main()
{
sum s1(1),s2(8,9);
//s1: x=1 y=10, s2: x=8 y =9
s1.displaydata();
s2.displaydata();
}

COPY CONSTRUCTORS

C++ calls a copy constructor to make a copy of an


object.
If there is no copy constructor defined for the class,
C++ uses the default copy constructor which copies
each field, ie, makes a shallow copy.
Constructors can accept arguments of any data type
including user defined data types and an object of its
own class
sum s1(10);
//Object created and initialized
sum s2(s1);
//Copy constructor
sum s3=s1;
//Copy constructor
sum s4;
s4=s1;
//Assignment

COPY CONSTRUCTORS
class sum
{
int x;
public:
sum(){ }
sum(int i) {x=i;}
sum(sum &j) {x=j.x;}
void displaydata() {
cout <<value of x = << x<<endl; }
};
void main()
{
sum s1(10);
sum s2(s1);
sum s3=s1;
sum s4;
s4=s1;
s1.displaydata();
s2.displaydata();
s3.displaydata();
s4.displaydata();
}

DYNAMIC CONSTRUCTORS
#include<string>
class String
{
char* data;
public:
String(const char* s = "")
{
data = new char[20];
strcpy(data,s);
}
~String() {
delete [] data;
}

int main()
{
String s = "hello";
String t = s; // same as String
t(s);
s.display( );
t.display( );
t.assign(world);
s.display( );
t.display( );
}

int size() const {


return strlen(data);
}
void assign(char str*) {
strcpy(data,str);
}

};

void display() {
cout << data;

PROPERTIES OF CONSTRUCTOR

A Constructor name must be the same as the class


name
They should be declared in the public section
They do not return any value(not even void)
They are invoked automatically when the objects are
created
Constructors are member functions so they can be
overloaded
Constructors are member functions so they can have
default arguments

PROPERTIES OF CONSTRUCTOR

They cannot ne inherited though they can be


called by a derived class.
Constructors cannot be virtual
They may not be static
We cannot refer to their addresses
They make implicit calls to the operators new
and delete when memory allocation required

DESTRUCTORS

A destructors, is used to destroy the


objects that have been created by a
constructor.
A destructor has the same name as the
constructor(which is same as the class
name) but is preceded by a tilde.
It performs clean up of the object ( in the
case of allocating memory inside the
object using new )
A destructor never takes any argument
nor does it return any value, thus cannot be

overloaded

DESTRUCTORS

Destructor is invoked implicitly by the compiler


upon exit from the program to clean up the
storage that is no longer accessible.
#include<iostream.h>
class example
{
private :
int data;
public:
example()
// constructor
{
cout << endl<<inside the constructor;
}

DESTRUCTORS
~example() // destructor (same name with tilde)
{
cout<<endl<<inside the destructor;
}
};
void main()
{
example e;
}

Output : inside the constructor


inside the destructor

PROPERTIES OF DESTRUCTOR

A destructor name must be same as of its class


name
It should be declared in public mode
It does not take any argument
They do not return any value(not even void)
It is invoked automatically when the objects are
destroyed
It cannot be overloaded
It cannot be inherited though it can be called by a
derived class
Destructor can be virtual
It may not be static
We cannot refer to its addresses

FRIEND FUNCTIONS

In principle, private and protected members of a


class cannot be accessed from outside the same
class in which they are declared.
But, then we can do it by declaring a prototype of
this external function within the class, and
preceding it with the keyword friend.

FRIEND FUNCTION CHARACTERISTICS


Friend functions:
The friend functions can serve, for example, to
conduct operations between two different classes.
It simply has access to its private and protected
members without being a member.
Friend classes:
Like friend function, there is also a provision in C++
for having friend classes.
Here an entire class is declared as friend for another
class.
When a class is declared as friend, it means the
members of the friend class have access to all the
public and private members of the class in which the
declaration was made.

FRIEND FUNCTIONS
#include <iostream>
using namespace std;
class CRectangle
{

int width, height;


public:
void set_values (int, int);
int area (void)
{
return (width * height);
}
friend CRectangle duplicate (CRectangle);
};

void CRectangle::set_values (int a, int b)


{
width = a;
height = b;
}

CRectangle duplicate (CRectangle rectparam)


{
CRectangle rectres;
rectres.width = rectparam.width*2;
rectres.height = rectparam.height*2;
return (rectres);
}
int main (void)
{
CRectangle rect, rectb;
rect.set_values (2,3);
rectb = duplicate (rect);
cout << rectb.area();
return 0;
}

FRIEND CLASS
#include <iostream>
class CSquare;

// pre-declaration

class CRectangle
{
int width, height;
public:
int area ()
{ return (width * height);
void convert (CSquare a);
};
class CSquare
{
private:
int side;
public:
void set_side (int a)
{
side=a; }
friend class CRectangle;
};

void CRectangle::convert (CSquare a)


{
width = a.side;
height = a.side;
}
int main ()
{
CSquare sqr;
CRectangle rect;
sqr.set_side(4);
rect.convert(sqr);
cout << rect.area();
return 0;
}

Vous aimerez peut-être aussi