Académique Documents
Professionnel Documents
Culture Documents
The class declaration describes the type and scope of its members. The class
function definitions describe how the functions are implemented.
The general form of a class declaration is:
Class Class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
The class declaration is similar to a struct declaration. The keyword class specifies
that what follows is an abstract data of type class_name. The body of class is
enclosed within braces and terminated by a semicolon. The class body contains the
declaration of variables and functions. These functions and variables are
collectively known as class members. They are usually grouped under two
sections, namely, private and public to denote which are the members are private
and which of them are public.
class student
{
int r_no; //variable declaration
char name; //private by default
public:
void getdata (int a, float b); //functions declaration
void putdata (void); //using prototype
};
Both of the objects Box1 and Box2 will have their own copy of data members.
int main( )
{
Box Box1; // Declare Box1 of type Box
Box Box2; // Declare Box2 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
volume = Box1.height * Box1.length * Box1.breadth;
cout << "Volume of Box1 : " << volume <<endl;
// volume of box 2
volume = Box2.height * Box2.length * Box2.breadth;
cout << "Volume of Box2 : " << volume <<endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
• Variables
• Pointers
• Function arguments and return types
• Class Data members
• Class Member functions
• Objects
When an object is declared or created with const, its data members can never be
changed, during object's lifetime.
Syntax:
const class_name object;
#include <iostream>
#include <string>
using namespace std;
class X
{
int i;
public:
X(int x)
{ i=x; }
int f() const
{ i++; }
int g()
{ i++; }
};
int main()
{
X obj1(10);
const X obj2(20); // Const Object
obj1.f();
obj2.f();
cout << obj1.i << obj2.i ;
obj1.g();
obj2.g();
}
Here, const member function never changes data members of class, and it can be
used with both const and non-const object. But a const object can't be used with a
member function which tries to change its data members.
class-name ∗ object-pointer ;
where class-name is the name of an already defined class and object-pointer is the
pointer to an object of this class type. For accessing normal data members we use
the dot (.) operator with object and (->) with pointer to object.
#include <iostream>
#include <string>
using namespace std;
class Data
{
public:
int a;
void print()
{
cout << "a is="<< a;
}
};
int main()
{
Data d, *dp;
dp = &d; // pointer to object
int Data::*ptr=&Data::a; // pointer to data member 'a'
d.*ptr=10;
d.print();
dp->*ptr=20;
dp->print();
}
Output will be:
p1.x = 10, p1.y = 15
p2.x = 10, p2.y = 15
2.5 Structures
Structure is the collection of variables of different types under a single name for better
visualisation of problem. Arrays is also collection of data but arrays can hold data of only one
type whereas structure can hold data of one or more types.
struct employee {
char name[50];
int age;
float salary;
};
The keyword struct declares employee as a new data type that can hold three fields
of different data type. The fields are known as Structure members or elements. The
identifier employee, which is referred to as structure name or structure tag, can be
used to create variable of type employee. For example:
Struct employee A;
A is variable of type employee and has three member variables as defined by the
template. Member variables can be accessed using the dot(.) operator. For
Example:
Strcpy(A.name,”john”)
Unit II
Chapter 3: Functions
3.1 Access functions
A class can have multiple public, protected, or private labelled sections. Each
section remains in effect until either another section label or the closing right brace
of the class body is seen. The default access for members and classes is private.
class Base
{
public:
// public members go here
protected:
// protected members go here
private:
// private members go here
};
A public member variable or function can be accessed anywhere in the program, or
even viewed from outside the class.
A private member function can only be called by another function that is member
of its class. Even an object cannot invoke a private function using (.) operator.
Consider the following example:
class sample
{
int m;
void read(void);
public:
void update(void);
void write(void);
};
The function read() is private member function it can be called outside the class by
the function update() which is public member of the same class.
void sample::update(void)
{
read();
}
• 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 entire program.
Static variables are normally used to maintain values common to the entire
class, a static data member can be used as a counter that records the
occurrences of all the objects.
Static member functions have a class scope and they do not have access to the “this
pointer” of the class. You could use a static member function to determine whether
some objects of the class have been created or not.
#include <iostream>
using namespace std;
class Box
{
public:
static int objectCount;
// Constructor definition
Box(double l=2.0, double b=2.0, double h=2.0)
{
cout <<"Constructor called." << endl;
length = l;
breadth = b;
height = h;
// Increase every time object is created
objectCount++;
}
double Volume()
{
return length * breadth * height;
}
static int getCount()
{
return objectCount;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
When above code is compiled and executed, produces the following result:
4.1 Constructors
A class constructor is a special member function of a class that is executed
whenever we create new objects of that class.
A constructor will have exact same name as the class and it does not have any
return type at all, not even void. Constructors can be very useful for setting
initial values for certain member variables.
private:
double length;
};
#include<iostream>
using namespace std;
class Point {
private:
int x;
int y;
public:
Point(int i = 0, int j = 0):x(i), y(j) {}
/* The above use of Initializer list is optional as the constructor can also
be written as:
Point(int i = 0, int j = 0) {
x = i;
y = j;
} */
int getX() const {return x;}
int getY() const {return y;}
};
int main() {
Point t1(10, 15);
cout<<"x = "<<t1.getX()<<", ";
cout<<"y = "<<t1.getY();
return 0;
}
Output will be
x = 10, y = 15
The above code is just an example for syntax of Initializer list. In the above
code, x and y can also be easily initialize inside the constructor.
4.3 The copy constructor
A copy constructor is a member function which initializes an object using
another object of the same class. A copy constructor has the following general
function prototype:
In C++, a Copy Constructor may be called in following cases:
1.When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an
argument.
3. When an object is constructed based on another object of the same class.
4. When compiler generates a temporary object.
If we don’t define our own copy constructor, the C++ compiler creates a
default copy constructor for each class which does a member wise copy
between objects. The compiler created copy constructor works fine in general.
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1)
{
x = x1; y = y1;
}
// Copy constructor
Point(const Point &p2)
{
x = p2.x; y = p2.y;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2 = p1; // Copy constructor is called here
// Let us access values assigned by constructors
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
The syntax for destructor is same as that for the constructor; the
class name is used for the name of destructor; with a tilde (~) sign as
prefix to it.
#include<iostream>
using namespace std;
class A
{
public:
A()
{
cout << "Constructor called\n";
}
~A()
{
cout << "Destructor called\n";
}
};
int main()
{
A obj1; // Constructor Called
int x=1;
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Constructor called
Constructor called
Destructor called
Destructor called
To understand the concept of returning an object by value from a function, consider this
example.
#include<iostream.h>
class weight
{
int kilogram;
int gram;
public:
void getdata ();
void putdata ();
void sum_weight (weight,weight) ;
weight sum_weight (weight) ;
};
void weight :: getdata()
{
cout<<"/nKilograms:";
cin>>kilogram;
cout<<"Grams:";
cin>>gram;
}
void weight :: putdata ()
{
cout<<kilogram<<" Kgs. and"<<gram<<" gros.\n";
}
weight weight :: sum_weight(weight w2)
{
weight temp;
temp.gram = gram + w2.gram;
temp.kilogram=temp.gram/1000;
temp.gram=temp.gram%1000;
temp.kilogram+=kilogram+w2.kilogram;
return(temp);
}
int main ()
{
weight w1,w2 ,w3;
cout<<"Enter weight in kilograms and grams\n";
cout<<"\n Enter weight 1" ;
w3=w1.sum_weight (w2);
wl.getdata();
cout<<" \n Enter weight 2" ;
w2.getdata();
w3.sum_weight(wl,w2);
cout<<"/n Weight 1 = ";
wl.putdata();
cout<<"Weight 2 = ";
w2.putdata();
cout<<"Total Weight = ";
w3.putdata();
return 0;
}
As the return type of function is weight (an object of class weight), a temporary object temp is
created within the function for holding return values. These values are accessed as temp
kilogram and temp gram by the function. When the control returns to main (), the object temp is
assigned to the object w3 in main().
Figure represents accessing of member variables within the function and returning a result from
the temporary object.
A friend function is a function that can access the private members of a class as though it were a
member of that class. In all other regards, the friend function is just like a normal function. A
friend function may be either a normal function, or a member function of another class. To
declare a friend function, simply use the friend keyword in front of the prototype of the function
you wish to be a friend of the class. It does not matter whether you declare the friend function in
the private or public section of the class.
Features
A friend function is not in the scope of the class, in which it has been declared as friend.
• It cannot be called using the object of that class.
• It can be invoked like a normal function without any object.
• Unlike member functions, it cannot use the member names directly.
• It can be declared in public or private part without affecting its meaning.
• Usually, it has objects as arguments.
int main()
{
Accumulator acc;
acc.add(5); // add 5 to the accumulator
reset(acc); // reset the accumulator to 0
return 0;
}
In this example, we’ve declared a function named reset() that takes an object of class
Accumulator, and sets the value of m_value to 0. Because reset() is not a member of the
Accumulator class, normally reset() would not be able to access the private members of
Accumulator. However, because Accumulator has specifically declared this reset() function to be
a friend of the class, the reset() function is given access to the private members of Accumulator.
Note that we have to pass an Accumulator object to reset(). This is because reset() is not a
member function. It does not have a *this pointer, nor does it have an Accumulator object to
work with, unless given one.
2.4 Friend classes
It is also possible to make an entire class a friend of another class. This gives all of the members
of the friend class access to the private members of the other class. Here is an example:
class Storage
{
private:
int m_nValue;
double m_dValue;
public:
Storage(int nValue, double dValue)
{
m_nValue = nValue;
m_dValue = dValue;
}
// Make the Display class a friend of Storage
friend class Display;
};
class Display
{
private:
bool m_displayIntFirst;
public:
Display(bool displayIntFirst)
{
m_displayIntFirst = displayIntFirst;
}
int main()
{
Storage storage(5, 6.7);
Display display(false);
display.displayItem(storage);
return 0;
}
Because the Display class is a friend of Storage, any of Display’s members that use a Storage
class object can access the private members of Storage directly. This program produces the
following result:
6.7 5
The ClassName must be an existing object. You can use your own object or one that shipped
with the compiler. After the asterisk operator, type a valid name for a C++ variable. The
dimension, which is (an estimate of) the number of elements of the array, is included in square
brackets.
After declaring the variable, you can initialize each member of the array using the new operator.
This operator allocates enough memory space for the member of the array. This means that the
initialization with the new operator can be followed by an actual initialization of the member
variables of the array.
To initialize a member of the array, you have various options. You must first call the new
operator for each member of the array. Once again, you can use one of the constructors. Consider
the above Cone object. We saw that one of its constructors took two arguments to create an
object. You can use such a constructor to initialize a member of the array.
Output :
10
In this case, as soon as the object is created the constructor is called which initializes its data
members.
A default constructor is so important for initialization of object members, that even if we do not
define a constructor explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
int side;
};
int main()
{
Cube c;
cout << c.side;
}
Output : 0
In this case, default constructor provided by the compiler will be called which will initialize the
object data members to default value, that will be 0 in this case.
2.7 Parameterised constructors
These are the constructors with parameter. Using this Constructor you can provide different
values to data members of different objects, by passing the appropriate values as argument.
Example :
class Cube
{
int side;
public:
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
OUTPUT : 10 20 30
By using parameterized constructor in above case, we have initialized 3 objects with user defined
values. We can have any number of parameters in a constructor.