0% found this document useful (0 votes)
13 views13 pages

Understanding Classes and Objects in C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views13 pages

Understanding Classes and Objects in C++

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT-2

CLASSES AND OBJECTS


6 CLASSES
SPECIFYING A CLASS
A class is a way to bind the data and its associated functions together. When
defining a class, we are creating a new abstract data type that can be treated like any
other built-in data type. a class specification has two parts:
1. class declaration
2. class function definitions
The class declaration describes the type and scope of its members.
The class function definitions describe how the class functions are implemented.

The general form class class_name


{
private:
variable declaration;
function declaration;
public:
variable declaration;
function declaration;
};

The keyword class specifies, that what follows is an abstract data of type
class_name. The body of a 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 called class members.
The keywords private and public are known as visibility labels. the class
members that have been declared as private can be accessed only from within the
[Link] the other hand, public members can be accessed from the outside the class.
By default, the members of a class are private. if both the labels are
missing, then, by default, all the members are private.
The variables declared inside the class are known as data members and the
functions are known as member functions.
Only the member functions can have access to the private data members and
private functions.
A SIMPLE CLASS EXAMPLE:
class item
{
int number; // variables declaration
float cost; // private by default
public:
void getdata (int a, float b); // functions declaration
void putdata (void); // using prototype

}:// ends with semicolon


the class variables are known as objects. Therefore, x is called an object of type
item.
EXAMPLE:
item x, y, z;
Objects can also be created when a class is defined by placing their names
immediately after the closing brace.
Class item
{ …….
…….
…….
} x, y, z;

ACCESSING CLASS MEMBERS:


The private data of a class can be accessed only through the member
functions of that class.
The following is the format for calling member function:
Object-name. function-name (actual-arguments);
For example
x. getdata (100,75.5);
is valid and assigns the value 100 to number and 75.5 to cost of the object x by
implementing the getdata() function.
DEFINING MEMBER FUNCTIONS
Member functions can be defined in two places:
 outside the class definition.
 Inside the class definition.
OUTSIDE THE CLASS DEFINITION
The general form
return-type class-name :: function-name (argument declaration)
{
Function body
}
The membership label class-name :: tells the compiler that the function function-
name belongs to the class-name. The symbol :: is called the scope resolution
operator.
void item :: getdata (int a, float b)
{
Number =a;
Cost =b;
}
INSIDE THE CLASS DEFINITION
The function declaration by the actual function definition inside the class.
For example, we could define the item class as follows:
class item
{
int number;
float cost;
public:
void getdata (int a, float b);

void putdata (void)


{
Cout << number << “\n”;

Cout << cost <<”\n”;


}
};
When a function is defined inside a class, it is treated as an inline function.
NESTING OF MEMBER FUNCTIONS:
A member function can be called by using its name inside another member
function of the same class. this is known as nesting of member functions.
Example
class sample
{
int m;
void read(void)
public:
void update()
{
read(); Nesting member function
}
void write()
};
PRIVATE MEMBER FUNCTIONS:
A private member function can only be called by another function that is a
member of its class. even an object cannot invoke a private function using the dot
operator.
Example
class sample
{
int m;
void read(void) private member function
public:
void update();
void write()
};
Sample program for member function
class set
{
int a,b;
int sum() private member function
{return(a+b);
}
public:
void getdata();
void disp()
{
Cout<<”SUM” << sum(); inside member function definition
} and nesting member function
};
void set :: getdata()
{
cout<<”Enter two number “;
cin>>a>>b; outside member function definition
}
void main()
{
set obj;
[Link]();
[Link]();
}
Output:
Enter two number 4 6 SUM 10
STATIC DATA MEMBERS
A data member of a class can be qualified as static.
Syntax is
static datatype variablename;
ex:
static int a;
Special characteristics:
 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
 It is visible only within the class, but its lifetime is the entire program.
 static variables are normally used to maintain values common to the entire
class.
Sample program
#include <iostream.h>
class count
{
static int n; declaration of static data member
public:
void getdata()
{
n++;
}
void disp();
{
Cout<<”count “<< n<<”\n”;
}
};
int count:: n;
void main()
{
count c1,c2;
[Link]();
[Link]();
[Link]();
[Link]();
}
Output is:
count 1
count 2
STATIC MEMBER FUNCTIONS
Like static member variable ,we can also have static member functions .
properties:
 A static function 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(instead of
its objects ) as follows

Class-name :: function-name;
Example
Count::disp();

Sample program
#include <iostream.h>
class count
{
static int n;
public:
void getdata()
{
n++;
}
static void disp(); static member function
{
Cout<<”count “<< n<<”\n”;
}
};
int count:: n;
void main()
{
count c1,c2;
[Link]();
count::disp(); accessing static function
[Link]();
count::disp();
}

Output is:
count 1
count 2
FRIENDLY FUNCTIONS:-
C++ allows the common function to be made friendly with both the classes .

Class ABCc
{
…………
…………

public:
………...
………...
Friend void xyz(void); //
declaration
};

The function declaration should be preceded by the keyword friend.


A function can be declared as a friend in any number of classes .
special characteristics:

 It is not in the scope of the class to which it has been declared


as friend.
 Since it is not in the scope of the class ,it cannot be called
using the object of that class.
 It can be invoked like a normal function without the help of
any object
 It can be declared either in the public or the private part of a
class without affecting its meaning.
 Usually , it has the object as arguments.
Member functions of one class can be friend functions of another class .
Sample Program
include<iostream.h>
class sample
{
int a;
int b;
public:
void setvalue()
{a=25;b=40; }
friend float mean(sample
s);
};
float mean(sample s)
{ return float(s.a+s.b)/2.0;
}
int main()
{
Sample x;
c. setvalue();
cout<<”mean value =
“<<mean(x)<<”\n”;
return 0;
}
Output:
Mean value =32.5
Array of objects in c++
Arrays are collection of similar data types. Arrays can be of any data
type including user defined data type. The array elements are stored in
continuous memory locations.
Example
#include <iostream.h> cout<<”Enter name and age of 3
class player players”;
{ for(int i=0;i<3;i++)
char name[20]; cricket[i].input();
int age; for(i=0;i<3;i++)
public: cricket[i].display();
void input() }
{
cout<<”Enter player name :”; Output :
cin>>name; Enter name and age of 3 players
cout<<”Age “; Enter player name : sachin
cin>>age; Age:40
} Enter player name:rahul
void display() Age : 38
{ Enter player name:saurav
cout<<”\nPlayer name :”<<name; Age:45
cout<<”\nAge :”<<age;
} Player name: sachin
}; Age:40
void main() Player name: rahul
{ Age:38
player cricket[3]; array of Player name: saurav
objects Age:45

In the example player is a user defined data type and can be used to declare an
array of object of type player.
Each object of an array has its own set of data variables.
Name
Age cricket[0]

Name
Age cricket[1] array of objects

Name
age cricket[2]

Overloading Member function


Overloading is nothing but one function is defined with multiple definitions with
same function name.
Example
#include <iostream.h>
#include <math.h>
class absv
{
public:
int num(int)
{
return(abs(x)); overloading member function
}
double num(double)
{
return(fabs(d)); overloading member function
}
};
void main()
{
absv n;
cout<<”absolute value of -25 is “<<[Link](-25);
cout<<”absolute value of -25.147 is “<<[Link](-25.147);
}

Output:
absolute value of 25
absolute value of 25.147
Bit fields and classes

- Bit field provides exact amount of bits required for storage of values.
- The number of bits required for a variable is specified by non negative
integer followed by colon.
- The variables occupy minimum one byte for char and two bytes for
integer.
- Arrays of bit fields are not permitted.
- Bit fields should have integral type.

For example
#define PETROL 1
#define FOUR_WH 4
#define NEW 6
class vehicle
{
private:
unsigned type :3;
unsigned fuel : 2; Bit fields
unsigned model :3;
public:
Vehicle()
{
type=FOUR_WH;
fFuel=PETROL;
model=NEW;
}
};
The colon(:) in the above declaration tells to the compiler that bit fields are used
in the class and the number after it indicates how many bits required to allot for
the field.

7. CONSTRUCTORS AND DESTRUCTORS


CONSTRUCTORS
A constructor is a ‘special’ member function whose task is to initialize the objects
of its class.
It is special because its name is the same as the class name.
The constructor is invoked whenever an object of its associated class is created.
A constructor is declared and defined as follows:

class integer
{
int m,n;
public:
integer(void); //constructor declared
……..
…….
};
integer :: integer(void); //constructor defined
{
M=0;n=0;
}

for example, the declaration integer int1;


A constructor that accepts no parameters is called the default constructor.
The constructor functions have some special characteristics. These are:
 They should be declare in the public section.
 They are invoked automatically when the objects are created.
 They do not have return types.
 They cannot be inherited, though a derived class can call the class
constructor.
 Constructors cannot be virtual.
 An object with a constructor cannot be used a member of a union.
Sample program
class integer
{
int m,n;
public:
interger() Default Constructor
Chap. 7 CONSTRUCTORS AND DESTRUCTORS

{
m=0;n=0;
}
void disp()
{
cout <<”M =”<<m++;
cout<<”N =”<<n++;
}
};
Void main()
{
integer i; invokes the default constructor of the compiler to create a object
[Link]();
}
Output:
M=1;
N=1;
PARAMETERIZED CONSTRUCTORS

C++ permits us to achieve this objective by passing arguments to the constructor


function when the objects are created. The constructors that can take arguments are
called parameterized constructors.
class integer
{
int m, n;
public:
integer(int x, int y); // parameterized constructor
…….
…….
};
integer :: integer(int x, int y)
{
m=x; n=y;
}

When a constructor has been parameterized, the object declaration statement such as
integer int; May not work.
We must pass the initial values as arguments to the constructor function when an
object is declared.
This can be done in two ways:
 By calling the constructor explicitly.
 By calling the constructor implicitly
first method :

Integer int1 = integer(0,100); // explicit call

This statement creates a integer object int1 and passes the values 0 and 100 to it .
Second method:
Integer int1 (0,100); //implicit call
Example
class integer
{
int m,n;
public:
interger(int [Link] y) parameterized constructor
{
m=x;n=y;
}
void disp()
{
cout <<”M =”<<m++;
cout<<”N =”<<n++;
}
};
Void main()
{
integer i(6,5); invokes the parameterized constructor
[Link]();
}

Output:
M=7;
N=6;
COPY CONSTRUCTOR
A copy constructor is used to declare and initialize an object from another
object. For example , the statement
integer I 2 (I1);
we would define the object I2 and at the same time initialize it to the values of I1.
Another form of this statement is
integer I 2=I1;
All copy constructor require one argument, with reference to an object of that class.
Example void show()
#include<iostream.h> {
class code cout<<n;
{ }
int n; };
public: void main()
code() {
{ code obj(50);
} code obj1(obj); invokes copy
code(int k) constructor
{n=k;} cout <<”Object obj value of n :\
code(code &j) copy n”<<[Link]();
constructor cout<<”Object obj1 value of n :\
{ n”<<[Link]();
n=j.n; }
}
Output : object obj1 value of n : 50
object obj value of n : 50
Explain DESTRUCTORS
Destructor are opposite to the constructor. The destructors have the same name
as their class, preceded by a tilde(~).
A destructor is automatically executed when object goes out of scope.
It is also invoked when delete operator is used to free memory allocated with
class pointer.
The class can have only one destructor.

Characteristics
 constructor, the destructor cannot be inherited.
 Constructor and destructor does not have return type.
 Only one destructor can be defined in a program.
 Programmer cannot access addresses of constructors and destructors.
 Destructors can be virtual,
 The destructors neither have default values nor can be overloaded.
 Constructors and destructors can make implicit calls to operators new
and delete if memory allocation/de allocation is needed for an object.
The general form is
~ destructor name()
{
body of the statement
}
ex: Destructor executed
~sample()
{
cout<<”Destructor executed”;
}

Example
class sample
{
sample()
{
cout<< “constructor executed”;
}
~sample()
{
cout<<”Destructor executed”;
}
};
void main()
{
sample s;
}

Output :
Costructor executed
Constructor and Destructor with static members
Every object has its own set of data members. Some times all the objects to share data fields
which is common for all the objects. If the member variable declared as static, only one copy of such
member is created for entire class.
Example
class man
{
static int nol
public:
man()
{
no++;
cout<<”Number of objects exist\n”<<no;
}
~man()
{
--no;
cout<<”Number of objects exist \n“<<no;
}
};
int man::no=0;
void main()
{
man A,B;
cout<<”Press any key to destroy object\n”;
}
Output:
Number of object exist 1
Number of object exist 2
Press any key to destroy object
Number of object exist 2
Number of object exist 1

You might also like