0% found this document useful (0 votes)
91 views27 pages

Unit1Notes Part 1

Uploaded by

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

Unit1Notes Part 1

Uploaded by

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

Unit 01: Basic Concepts of OOP, Classes and objects

Contents:
What is object oriented programming? Why do we need object-oriented Programming?
Application and Characteristics of object oriented languages. Basic concepts of Object Oriented
Programming: Encapsulation, Abstraction, Inheritance, Polymorphism, Dynamic Binding,
Message Passing, class and object. Structure of C++ program, Compiling and Executing C++
Programs. Classes: Specifying Class, Access Specifies, Defining Data member and member
function. Objects: Creating Object, memory allocation for object, Operators in C++: The Scope
resolution operator, The arrow operator, memory management operator, type casting, Pointer to
object, The 'this' pointer, Objects and Arrays: Array of Objects, Arrays inside objects.
Namespaces, Nested/Inner Classes.

Object Oriented Programming:


Object oriented programming can be defined as a programming model which is based upon the
concept of objects. Objects contain data in the form of attributes and code in the form of
methods. In object oriented programming, computer programs are designed using the concept of
objects that interact with real world. Object oriented programming languages are various but the
most popular ones are class-based, meaning that objects are instances of classes, which also
determine their types.
Languages used as Object Oriented Programming
Java, C++, C#, Python,
PHP, JavaScript, Ruby, Perl,
Objective-C, Dart, Swift, Scala.

Characteristics of POP:
1) It emphasis on doing things i.e. Algorithm.
2) Large programs are divided into smaller program known as function.
3) Most of the function shares global data.
4) Data move openly around the system from function to function.
5) Function transforms data from one form to another.
6) It follows top down approach in program design.

Features of OOP:
1) It emphasis on data rather than procedure.
2) Programs are divided into objects.
3) Objects are characterized by functions that operate on data.
4) Functions that operate on data of the object are tied together in data structure.
5) Data is hidden and cannot be access by external function.
6) Object communicates with each other through function.
7) New data and function can be easily added whenever necessary.
8) It follows bottom up approach in program design.

Differences Between POP And OOP:


To summarize, few important differences between POP and OOP are as follows:
POP :
1) It is procedure or action oriented.
2) Unit of program is function.
3) Group of function is a program.
4) It emphasis on algorithm.
5) It follows top down approach.
OOP
1) It is object oriented
2) Unit of program is object.
3) User-define type of classes and objects to form program.
4) It emphasis on data.
5) It follows bottom up approach.

Sr. Key OOP POP


No.
1 Definition OOP stands for Object Oriented POP stands for Procedural
Programming. Oriented Programming.
2 Approach OOP follows bottom up approach. POP follows top down approach.

3 Division A program is divided to objects A program is divided into


and their interactions. functions and they interacts.
4 Inheritance Inheritance is supported. Inheritance is not supported.
supported
5 Access control Access control is supported via No access modifiers are supported.
access modifiers.
6 Data Hiding Encapsulation is used to hide No data hiding present. Data is
data. globally accessible.
7 Example C++, Java C, Pascal
Basic Concepts of OOP:
1) Object
2) Class
3) Data abstraction and encapsulation
4) Inheritance
5) Polymorphism
6) Dynamic binding
7) Message passing

Let’s see these one by one.


1) Objects :
Objects are basic run time entities and form a distinguishable real time entity. e.g. object
may represent a person, place, bank account, Roll Number of class etc. Program object
should be chosen such that they match closely with real world objects. Each object
contains data and code to manipulate the data. They take up a space in memory and have
associated address. An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is allocated.

2) Class :
The building block of C++ that leads to Object-Oriented programming is a Class.
It is a user-defined data type, which holds its own data members and member functions,
which can be accessed and used by creating an instance of that class. A class is like a
blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names
and brand but all of them will share some common properties like all of them will have 4
wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed
limits, mileage are their properties.

A class is group of objects with similar attributes and common relationship to other
objects i.e. class is collection of objects of similar type. Objects are variables of type
class. Classes are user define data types and behaves like any other built-in type. Once a
class is defined we can create any number of objects belonging to that class.
3) Data Abstraction and Encapsulation :
The wrapping of data and functions into a single unit (class) is called as encapsulation.
The data is not accessible to the outside world and only the function of that class can
access its data. This insulation of data from direct access by a program is called data
hiding or information hiding. Abstraction refers to the act of representing essential
features without including the background details. Classes use the concept of abstraction
and encapsulate all essential properties of objects that are to be created. The attributes are
sometime called as data members and the functions that operate on these data are called
as methods or member function. Classes are also known as Abstract Data Types (ABT)
as they uses concept of data abstraction.
4) Inheritance :
It is the process by which objects of one class acquire the properties of objects of another
class. It also means defining a new objects in terms of old one. It gives the idea of
reusability. One class of object inherits (reuse) data and behavior from another class, and
thus form hierarchy among classes in which child class is inheritaed from its parent class.
Parent class is called as base class and child class is called as derived class. Base class
also known as super class and derive class as sub class. Thus we can add additional
features to an existing class without modifying it. OOP’s also support multiple
inheritance which means class can be derived from more than one base class. In fig. 1.4
Class Bird is Base class. Flying Birds and Non-flying Birds are child classes.

5) Polymorphism :
It means ability to take more than one form. It refers to single operation can have
different behavior in different object i.e. different object react differently to same
message where behavior depends upon types of data used for operation.
e.g. Operation of addition : It will generate a sum if data is two number. If data is string,
operation will produce a third string by concatenation operation.

x + y = Sum, if x and y are nos.


x + y = String, if x and y are strings
The process of making an operator to perform different functions in different instances is
known as operator overloading. Using a single function name to perform different types
of task is called as function overloading.
6) Dynamic binding :
It is also called as late binding which means that code associated with a given procedure
call is not known until time of the call at run time. It is associated with polymorphism and
inheritance.
7) Message passing :
OOPs consists of objects and classes. It consists of set of objects, which communicate
with each other by sending and receiving information. A message for object is request for
execution of function and that function will generate result in receiving object. Message
passing envolves specifying name of object, name of function (message) and the
information to be send.

e.g. a function call is:


employee.salary (name);
where, employee is object, salary is message or function and name is information.

Advantages of OOP:
OOP focuses on identifying objects from application and writing procedures around those
objects. Following are advantages of OOPs.
1) By using inheritance we can eliminate a redundant code and extend use of existing class.
2) Encapsulations helps to built a protected program that cannot be access by other parts of
program.
3) One can have multiple objects without any interference.
4) We can divide program classes and objects.
5) Interference with external system is simple by using message passing.
6) It supports reusability, which reduces design, coding and testing cost of software.
7) OOPs system can be easily upgraded from small to large system.
8) Software complexity can be easily managed.

Application of C++:
1) Since C++ allow us to create hierarchy related objects, we can build special object-
oriented libraries which can be used later by many programmers.
2) While C++ is able to map the real-world problem properly, the C part of C++ gives the
language the ability to get closed to the machine-level details.
3) C++ programs are easily maintainable and expandable. When a new feature needs to
be implemented, it is very easy to add to the existing structure of an object.
Application of OOP:
The promising areas of application of OOP include:
1) Real-time system
2) Simulation and modeling
3) Object-oriented data bases
4) Hypertext, Hypermedia, and expertext
5) AI and expert systems
6) Neural networks and parallel programming
7) Decision support and office automation systems
8) CIM/CAM/CAD systems

A Simple C++ Program:

// My first C++ program


# include <iostream.h>
void main ()
{
cout << “Hello”;
}

Above program display the output as ‘Hello’ on your screen.


Features of a program are as follows.

1) Comments :
(// - double slash) is a new comment symbol. It may start anywhere in the line and
whatever follows till the end of line is ignore. It is basically single line comment and
multi-line comment can be written as follows
// This is example
// of C ++ prg.
The comment symbol of C is (/* */) is still valid in C ++
2) Output Operator :
cout << “Hello”;
Above statement displays a string in quotation marks on the screen. Cout is a identifier
and is predefined object that represents standard output in C ++. The output can be
redirected to other output devices also. The operator ‘<<’ is called as ‘insertion’ or ‘put
to’ operator. It inserts (sends) the content of variable on its right to the object on its left.
Printf statement can also be use for displaying output in C ++.
Fig: Output using Insertion operator

3) iostream File :

# include <iostream.h>
# include directive causes the pre-processor to add the contents of iostream file to the
program. For example this file contain declaration for the identifier as ‘cout’ and ‘cin.’ and
operator <<,>>.
4) Return type of main :
In C ++, main () returns integer type values. Therefore every main () in C++ should end
with ‘return’ statement and return type for main should be explicitly specified as int.
Otherwise program will give a warning.
5) Variables :
All the variables of program must be declared before they are used in program e.g. int
a,b,c;
6) Input operator :

The statement cin >>number; a is called as input statement. It causes program to wait for
a user to type a number. The number entered is placed in variable ‘a’. The identifier cin is
pre-defined object that represents standard input stream. Here input stream represents
keyboard. The operator >> is called as extraction or ‘get from’ operator. It extracts
(takes) value from keyboard and assigns it to the variable on its right.

Fig: Input using Extraction operator

7) Cascading of I/O operators


e.g. cout << “SUM =” <<c;
It sends the string SUM = to cout and then sends the value of c. Multiple use of insertion
(<<) or (>>) operator is called cascading.
e. g. cin >> a >> b;
Here the values accepted are assigned to the variables from left to right. i.e. first value
entered will be stored in a and second value in b.

Sample Program 1 :
Write a program to accept radius from user and find out area of circle.

# include <iostream.h>
void main ()
{
float r, area, pi;
clrscr ( );
cout << “enter the radius of circle to find the area of that circle”;
cin >> r;
pi = 3.14;
area = pi * r * r;
cout << “area of circle =” << area;
getch ();

Structure of C++ Program


A typical C++ program would contain four sections as shown in fig. These sections may be placed
in separate code files and then compiled independently or jointly. It is a common practice to
organize a program into three separate files: The class declarations are placed in a header file and
the definitions of member functions go into another file. This approach enables the programmer to
separate the abstract specification of the interface from the implementation details (member
function definition).
Finally, the main program that uses the class is placed in a third file which “includes: the
previous two files as well as any other file required.
Fig: Structure of C++ Program

This approach is based on the concept of client-server model as shown in following fig. The
class definition including the member functions constitute the server that provides services to the
main program known as client. The client uses the server through the public interface of the
class.

Fig: client-server model


Keywords / Reserved Words :
The keywords used in C / C++ have special meaning to the compiler. The programmer
can’t use these words for identifiers such as variable names.

The standard reserved keywords are:

asm, auto, bool, break, case, catch, char, class, const, const_cast, continue, default,
delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false, float, for,
friend, goto, if, inline, int, long, mutable, namespace, new, operator, private, protected,
public, register, einterpret_cast, return, short, signed, sizeof, static, static_cast, struct,
switch, template, this, throw, true, try, typedef, typeid, typename, union, unsigned, using,
virtual, void, volatile, wchar_t, while

Identifiers :
- Identifiers Simply references to memory locations, which can hold values (data).

- To put in other words Identifiers refers to names of variables, functions, arrays, classes
etc. created by programmer.

- Are formed by combining letters (both upper and lowercase), digits (0–9) and
underscore ( _).

- Rules for identifier naming are:

1. The first character of an identifier must be a letter, an underscore ( _ ) also


counts as a letter.

2. The blank or white space character is not permitted in an identifier.

3. Can be of any length.

4. Reserved words/keywords and characters such as main and # cannot be used.

The C++ language is a "case sensitive" language. That means that an identifier written in capital
letters is not equivalent to another one with the same name but written in small letters. Thus, for
example, the RESULT variable is not the same as the result variable or the Result variable.
These are three different variable identifiers.
Constants:

Constants refer to the fixed values that do not change during the execution of the program. C++
supports several kinds of literal constants. They include characters, floating point numbers and
strings.

Example:

123 // decimal integer constant


12.34 // floating point constant
“C++” // String constant
‘C’ // character constant

To declare a constant, use keyword const as shown in the following variable declaration
example:
const int day_in_week = 7;
const float total_loan = 1100000.35;

Variables :
- Identifier that value may change during the program execution.

- Every variable stored in the computer’s memory has a name, a value and a type.

- All variable in a C / C++ program must be declared before they can be used in the
program.

- A variable name in C / C++ is any valid identifier, and must obey the rules mentioned
above.

Initializing a variable means, give a value to the variable, that is the variable’s initial
value and can be changed later on.
- Variable name are said to be lvalue (left value) because they can be used on the left side
of an assignment operator.
- Constant are said to be rvalue (right value) because they only can be used on the right
side of an assignment operator. For example:

x = 20;
x is lvalue, 20 is rvalue.

Note that lvalue can also be used as rvalue, but not vice versa.
General form:
data_type variable_name;
Example of the variable declaration
int m, n;
float total, rate;
char user_response;
char color[7];

and then initialize:

n = 20;
rate = 4.5;
user_response = ‘n’;
color = "green";

Declaring and initializing variables in one line examples:


int m, n = 10;
char * ptr = "TESTING";
float total, rate = 0.5;
char user_response = ‘n’;
char color[7] = "green";

Basic Data types:

When programming, we store the variables in our computer's memory, but the computer has to
know what kind of data we want to store in them, since it is not going to occupy the same
amount of memory. So we need to declare a data type so that computer can allocate required
memory to it. Data types in C++ can be classified under various catagories as shown in following
figure of Hierarchy of data types.
Figure: Hierarchy of data types.

Built-in data types are also known as Basic data types or Fundamental data types.

Basic data type (int, char and float) and their the range of values that can be
represented with each one are shown in Table :
C++ Operators:

1. Basic Operators:
All basic operators of C works in c++ with same meaning and syntax
a. Assignment (=)
The assignment operator assigns a value to a variable.
a = 5;
This statement assigns the integer value 5 to the variable a.

a = b;
This statement assigns to variable a (the lvalue) the value contained in variable b (the rvalue).

b. Arithmetic operators ( +, -, *, /, % )
The five arithmetical operations supported by the C++ language are:
+ addition
- subtraction
* multiplication
/ division
% modulo

c. Increment (++) and Decrement (--) operators

They increase or reduce by one the value stored in a variable. They are equivalent to +=1 and
to - =1,
e.g a++;
b--;
d. Relational and equality operators ( ==, !=, >, <, >=, <= )
In order to evaluate a comparison between two expressions we can use the relational and
equality operators

e. Logical operators ( !, &&, || )


! : Boolean operation NOT
&& : Boolean operation AND
|| : Boolean operation OR

f. Conditional operator ( ? )
The conditional operator evaluates an expression returning a value if that expression is true
and a different one if the expression is evaluated as false. Its format is:
condition ? result1 : result2
e.g (a>b) ? a : b;
g. sizeof() operator

This operator accepts one parameter, which can be either a type or a variable itself and
returns the size in bytes of that type or object:
a = sizeof (char);
This will assign the value 1 to a because char is a one-byte long type.

a = sizeof (int);
This will assign the value 2 to a because int is a two-byte long type.

2. Scope resolution Operator:

The operator (::, two colons) is called as scope resolution operator. It is used to define a member
of a class from outside the class definition itself. The scope operator (::) specifies the class to
which the member being declared belongs, This operator helps in defining the member function
outside the class.

The syntax for a member function definition outside the class definition is :

return_type name_of_the_class::function_name (argument list)


{
//body of function
}

Eg.
Void SYIT :: getdata()
{ // body of function
}

3. Memory management Operator:

When we declare variables in program, by default fixed amount of memory ( as decided by


computer for example as per above table) is allotted in advance. But, what if we need a variable
amount of memory that can only be determined during runtime? For example, in the case we
need some user input to determine the necessary amount of memory space. Then in this case
dynamic memory allocation is used , for which C++ uses the operators: new and delete.

‘new’ Operator:

In order to request dynamic memory we use the operator new.

General form:
pointer = new datatype;
It returns a pointer to the beginning of the new block of memory allocated.

e.g. int *p;


p=new int;
For example:
int * bobby;
bobby = new int [5];
In this case, the system dynamically assigns space for five elements of type int and returns a
pointer to the first element of the sequence, which is assigned to bobby. Therefore, now, bobby
points to a valid block of memory with space for five elements of type int.

The difference between declaring a normal array and assigning dynamic memory to a Pointer:
The most important difference is that the size of an array has to be a constant value, which limits
its size to what we decide at the moment of designing the program, before its execution, whereas
the dynamic memory allocation allows us to assign memory during the execution of the program
(runtime) using any variable or constant value as its size.

‘delete’ Operator:

Since the necessity of dynamic memory is usually limited to specific moments within a program,
once it is no longer needed it should be freed so that the memory becomes available again for
other requests of dynamic memory. This is the purpose of the operator delete.
General format is:
delete pointer;
delete [] pointer;
The first expression should be used to delete memory allocated for a single element, and the
second one for memory allocated for arrays of elements.
The value passed as argument to delete must be a pointer to a memory block previously
allocated with new operator.
e.g delete p ;

CLASS AND OBJECT:


Definition And Declaration Of A Class:
A class is an expanded concept of a data structure: instead of holding only data, it can hold both
data and functions. A class in C++ combines related data and functions together.

The class specification can be done in two part:


(i) Class declaration : It describes both data members and member functions.
(ii) Class function definitions : It describes class member functions definitions.
The syntax of a class declaration is shown below :
Class name_of _class
{
private : variable declaration; // data member
Function declaration; // Member Function (Method)
public : variable declaration;
Function declaration;
};

Where, ‘class’ is keyword used to define class as data type. name_of _class is user
defined name for the class.

Access Specifiers(Visibility Modes):


The body of the class has two keywords namely :

(i) private (ii) public


In C++, the keywords private and public are called access specifiers. The data hiding
concept in C++ is achieved by using the keyword private. Private data and functions can only be
accessed from within the class itself( and not in main() function). Public data and functions are
accessible outside the class also (are accessible in main() function also).
The data declared under Private section are hidden and safe from accidental manipulation.
Though the user can use the private data but not by accident.
The functions that operate on the data are generally public so that they can be accessed
from outside the class but this is not a rule that we must follow.
By default, all members of a class declared with the class keyword have private access
for all its members.

e.g
class SYIT
{
private:
int Roll;
char name[20];
public:
void getdata();
void putdata();
};
Creating object of a class (DECLARATION OF OBJECTS )
The objects of a class are declared after the class definition. One must remember that a class
definition does not define any objects of its type, but it defines the properties of a class. For
utilizing the defined class, we need variables of the class type (i.e. object).
Once class is defined, we can create object later in main function as :
Syntax: Class_name object _name;
e.g. void main()
{ SYIT S1;
---
----
}
Where S1 is said to be object of class SYIT.
Objects can also be created immediately when class is defined by placing object name after class
closing brace and before semicolon as:
class class_name
{ -----
-----
}objectname;
For example,
class SYIT
{
Private:
int Roll;
char name[20];
public:
void getdata();
void putdata();
}s1;

MEMBER FUNCTION DEFINITION:


In C++, the member functions can be defined in two ways :
(a) Inside class definition
(b) Outside class definition using scope resolution operator (::)

The code of the function is same in both the cases, but the function header is different as
explained below :
a) Defining Member Function Inside Class Definition
One can replace function declaration by actual function definition inside class
as shown in following example
class SYIT
{ private:
int rollno :
public;
void getdata ( )
{ cout << “enter your Roll no”;
cin >> rollno;
}
} x;
When function is define inside a class as above example is treated as inline function.
Normally small function is defined inside class.

b) Defining Member Function Outside Class Definition


Member function that are declare inside a class have to be define separately
outside the class.
The general format of member function definition outside a class is :
returntype classname : : function name (actual arguments)
{ ------ }
Here the classname : : tells the compiler that the function belongs to class, class name.
Example
class SYIT
{ private:
int roll no;
public :
void getdata ( ); //function declaration
}x;

void SYIT :: getdata ( ) //function definition outside class


{
cout << “enter your Roll no”;
cin >> rollno;
}

main ( )
{
// body of main function
}

‘SYIT :: ’ is also called as membership label and the operator ‘::’ is called as scope resolution
operator.
Example program using class:
1. WAP to create a class SYIT having data members as Roll and name. Accept this data and
display for one object of class. Define member function outside of class.

#include<iostream.h>
#include<conio.h>
class SYIT // class definition
{
private:
int Roll;
char name[20];
public:
void getdata(); // function declaration
void putdata(); // function declaration
}s1; // end of class

void SYIT :: getdata ( ) //function definition outside class


{
cout << “enter your Roll no and name : ”;
cin >> Roll>>name;
}

void SYIT :: putdata ( ) //function definition outside class


{
cout<< “ your roll no = “ <<Roll;
cout<< “ your Name = “ <<name;
}

void main ( )
{
clrscr(0;
s1.getdata(); // function call
s1.putdata(); // function call
getch();

}
2. WAP to create a class SYIT having data members as Roll and name. Accept this data
and display for one object of class. Define member function inside of class.

#include<iostream.h>
#include<conio.h>
class SYIT // class definition
{
private:
int Roll;
char name[20];
public:
void getdata ( ) //function definition inside class
{
cout << “enter your Roll no and name : ”;
cin >> Roll>>name;
}

void putdata ( ) //function definition intside class


{
cout<< “ your roll no = “ <<Roll;
cout<< “ your Name = “ <<name;
}
}s1; // end of class

void main ( )
{
clrscr(0;
s1.getdata(); // function call
s1.putdata(); // function call
getch();

Characteristics of Member Functions:


1) Several different classes can use same function name. The membership label will resolve their
scope.
2) Member function can access private data of class where as non-member function cannot do so.
3) A member function can call another member function of same class directly without using dot
operator.

Making Outside Function as Inline:


When function is define inside a class is treated as inline function. Normally small function is
defined inside class. We can define member function outside the class definition and still make it
inline. Just by using a qualifier inline in the header line of function definition.
e.g. class SYIT
{
public :
void getdata ( ); // declaration
};

inline void SYIT : : getdata ( )


{ }

ACCESS SPECIFIERS (VISIBILITY MODES):


The access restriction to the class members is specified by the labeled public, private, and
protected sections within the class body. The keywords public, private, and protected are called
access specifiers.
The public Members A public member is accessible from anywhere outside the class but within a
program.

A private member variable or function cannot be accessed, or even viewed from outside the
class. Only the class and friend functions can access private members. By default all the
members of a class would be private, for example in the following class width is a private
member, which means until you label a member, it will be assumed a private member –
class Box
{
double width;

public:
double length;
void setWidth( double wid );
double getWidth( void );
};

Practically, we define data in private section and related functions in public section so that they
can be called from outside of the class as shown in the following program.

#include <iostream>
using namespace std;
class Box {
public:
double length;
void setWidth( double wid );
double getWidth( void );
private:
double width;
};

// Member functions definitions


double Box::getWidth(void) {
return width ;
}
void Box::setWidth( double wid ) {
width = wid;
}
// Main function for the program
int main() {
Box box;
// set box length without member function
box.length = 10.0; // OK: because length is public
cout << "Length of box : " << box.length <<endl;
// set box width without member function
// box.width = 10.0; // Error: because width is private
box.setWidth(10.0); // Use member function to set it.
cout << "Width of box : " << box.getWidth() <<endl;
return 0;
}
MEMORY ALLOCATION FOR OBJECT:

In C++, all the member functions of a class are created and stored when the class is defined and
this memory space can be accessed by all the objects related to that class.
Memory space is allocated separately to each object for their data members. Member variables
store different values for different objects of a class.
The figure shows this concept.

Eg:
class SYIT
{ private:
int roll;
char name[20];
public:
void getdata();
void putdata();
}s1,s2;
From above example:
Memory allotted for data variables:
Then memory allotted to object s1 :

roll name

Again separate memory allotted to roll and name for object s2:

roll name

Common Memory allotted to functions for object s1 and s2:

getdata()
Memory for object s1 as well s2.

putdata() Memory for object s1 as well s2.

ARRAY OF OBJECTS:

Each class has it’s own object. i.e. we can have variable of type class. In a same way we can have
array of variable of the type class such variable are called as array of an object. The syntax for
declaring and using object array is same as it is for any other type of array.
Array of object of class is created in same way as single object of class is created as:
Syntax:
class class_name
{ -----
-----
} objectArrayname[size];

e.g
class SYIT
{ ---
-----
} S[5];

It will create S as array of 5objects of class SYIT.

Generally it is used when we need more than one object for a same class.
Example Program:
1) To accept and display roll no and name of 3 students, following program uses array of three
objects.
#include<iostream.h>
#include<conio.h>
class SYIT
{ provate:
int Roll_no;
char name [20];
public :
void getdata ( );
void displaydata ( );
} stud [3];

void SYIT : : getdata ( )


{
cout << “Enter your roll no and name”;
cin >> Roll_no >> name;
}

void SYIT : : displaydata ( )


{ cout << “Roll_no =” << roll no;
cout << “Name =” << name;
}

main ()
{ int i;
for (i = 0; i < 3; i++) //Accept data 3 times
{
stud(i).getdata(); // function call
}

for (i = 0; i < 3; i++) //Display data 3 times

{
stud(i).displaydata(); // function call

getch();
return(0);
}

You might also like