0% found this document useful (0 votes)
56 views29 pages

Oops Unit 1 Preeti

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)
56 views29 pages

Oops Unit 1 Preeti

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/ 29

Object Oriented Programming

Unit-1:

Introduction to different programming paradigm, characteristics of


OOP, Class, Object, Data members, Member functions, Structures in
C++, Different access specifiers, Defining ember functions inside and
outside the class, Array of objects

 Programming paradigms

Programming paradigms are different ways or styles in which a given program


or programming language can be organized. Each paradigm consists of certain
structures, features, and opinions about how common programming problems
should be tackled.

The question of why are there many different programming paradigms is similar
to why are there many programming languages. Certain paradigms are better
suited for certain types of problems, so it makes sense to use different
paradigms for different kinds of projects.
 Imperative paradigm
The imperative paradigm is said to be command driven. The program code in
imperative paradigm directs the program execution as sequence of statements
executed one by one.
The imperative style program consists of set of program statements. Each
statement directs the computer to perform the specific task.
In imperative style program, the programmer has to elaborate each statement in
details. Each statement directs what is to be done and how it is to be done.
The execution of the program statement is decided by the control flow
statements. And the program flow can be directed as per the program logic.
Examples: Fortan, Algol, Pascal, Basic

 Declarative paradigm
The declarative paradigm is a programming paradigm that is focused on the
logic of the program and the end result. In this paradigm, control flow is not an
important element of the program.
The main focus of the declarative style of programming is achieving the end
result. This paradigm is straight forward and to the point while writing the
program code.
 Procedural Programming
The program based on procedural paradigm consists of set of procedures. The
procedures are also referred as function, method or subroutines.
The program structure in procedural programming consists of set of functions.
Each performs a specific operation.
The function consist of group of computational steps that directs the computer
to perform specific operation. The function once defined can be called many
times in the program to repeat the same operation.
The programmer can either use standard library functions or create library of
user defined functions
The C programming language is the most commonly used and popular language
that is still used in the software industry.
 Object oriented Paradigm
The object oriented is a type of structured programming that views the program
components as objects. In OOP programming, all the program components are
represented as objects.
An object binds the data and associated methods together as single unit. As such
the programmer can control the data access permissions by defining the access
specifier.
The OOP programming protects the program data from inadvertent operations
by another methods. And therefore, the object oriented programming offers
robust security features.
The OOP paradigm compliant languages such as C++, Java and Python are
extensively used for enterprise level software projects.
 Parallel processing approach –

Parallel processing is the processing of program instructions by dividing them


among multiple processors. A parallel processing system posses many numbers
of processor with the objective of running a program in less time by dividing
them. This approach seems to be like divide and conquer, Examples are NESL
and C/C++ also supports because of some library function.
 Logic Programming
The logic programming is a declarative programming paradigm that is based on
the logic and control. The term logic essentially means facts and rules. Whereas
the control means an order of rules.
The term algorithm is defied a s logic plus control(logic+control).The logic
defines what should be solved whereas the control defines how it should be
solved.
The main advantage of the logic programming is that the programmer needs to
simply define the what part of the problem and system finds out the best
solution to the problem.
The program written in logic programming language consists of set of program
statements in the logical form. Each statement is an expression of facts, rules
and the order of rules.
The logic programming is an abstract model of computation. It is based on the
first order predicated logic. The predicate logic is also referred to as fist order
logic.
The clauses re an important element of the logic programming. In other words,
a logic program is a set of clauses.
Example: Prolog
 Functional Paradigm
The functional programming comes under declarative paradigm. The
declarative paradigm focuses on what is to be solved. Whereas the imperative
approach focuses on how it is to be solved.
As the name suggest, the functional programming is based on the mathematical
functions. The functional programming attempts to solve the problem by
composing mathematical functions as program components.
In functional programming style, the computer program is created with the
application and composing the mathematical functions.
In functional programming, the program written in programming language will
always produce output exactly similar to its equivalent mathematical function.

 Data base Query Language


The database query language such as SQL(Structured Query Language)is the
most commonly used example of model based language.
The database is vital component of most software projects. Most
RDBMS(Relational Database Management system) support the SQL for
database programming.
The software application communicates with the RDBMS with the help of SQL
commands. The RDBMS in turn communicates with the database and executes
the SQL commands to perform the desired database operations.
The database query language is also alternately referred to as model based
programming.

 Basic Characteristics of Object-Oriented Programming:


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 a user-defined data-type which has data members and
member functions.
 Data members are the data variables and member functions are the
functions used to manipulate these variables and together these
data members and member functions define the properties and
behaviour of the objects in a Class.
 In the above example of class Car, the data member will be speed
limit, mileage etc and member functions can apply brakes, increase
speed etc.
We can say that a Class in C++ is a blue-print representing a group of
objects which shares some common properties and behaviours.

Object
An Object is an identifiable entity with some characteristics and behaviour.
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.

class person
{
char name[20];
int id;
public:
void getdetails(){}
};

int main()
{
person p1; // p1 is a object
}

Object take up space in memory and have an associated address like a record
in pascal or structure or union in C.
When a program is executed the objects interact by sending messages to one
another.
Each object contains data and code to manipulate the data. Objects can interact
without having to know details of each other’s data or code, it is sufficient to
know the type of message accepted and type of response returned by the
objects.
Encapsulation:

In normal terms, Encapsulation is defined as wrapping up of data and


information under a single unit. In Object-Oriented Programming,
Encapsulation is defined as binding together the data and the functions that
manipulate them.
Consider a real-life example of encapsulation, in a company, there are
different sections like the accounts section, finance section, sales section etc.
The finance section handles all the financial transactions and keeps records of
all the data related to finance. Similarly, the sales section handles all the sales-
related activities and keeps records of all the sales. Now there may arise a
situation when for some reason an official from the finance section needs all
the data about sales in a particular month. In this case, he is not allowed to
directly access the data of the sales section. He will first have to contact some
other officer in the sales section and then request him to give the particular
data. This is what encapsulation is. Here the data of the sales section and the
employees that can manipulate them are wrapped under a single name “sales
section”.
Encapsulation also leads to data abstraction or hiding. As using encapsulation
also hides the data. In the above example, the data of any of the section like
sales, finance or accounts are hidden from any other section.

Abstraction:

Data abstraction is one of the most essential and important features of object-
oriented programming in C++. Abstraction means displaying only essential
information and hiding the details. Data abstraction refers to providing only
essential information about the data to the outside world, hiding the
background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the speed of the car or applying brakes
will stop the car but he does not know about how on pressing accelerator the
speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of accelerator, brakes etc in the car. This is what
abstraction is.
 Abstraction using Classes: We can implement Abstraction in C++
using classes. The class helps us to group data members and member
functions using available access specifiers. A Class can decide which
data member will be visible to the outside world and which is not.
 Abstraction in Header files: One more type of abstraction in C++ can
be header files. For example, consider the pow() method present in
math.h header file. Whenever we need to calculate the power of a
number, we simply call the function pow() present in the math.h
header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually
calculating the power of numbers.

Polymorphism:

The word polymorphism means having many forms. In simple words, we can
define polymorphism as the ability of a message to be displayed in more than
one form.
A person at the same time can have different characteristic. Like a man at the
same time is a father, a husband, an employee. So the same person posses
different behaviour in different situations. This is called polymorphism.
An operation may exhibit different behaviours in different instances. The
behaviour depends upon the types of data used in the operation.
C++ supports operator overloading and function overloading.
 Operator Overloading: The process of making an operator to exhibit
different behaviours in different instances is known as operator
overloading.
 Function Overloading: Function overloading is using a single
function name to perform different types of tasks.
Polymorphism is extensively used in implementing inheritance.
Example: Suppose we have to write a function to add some integers, some
times there are 2 integers, some times there are 3 integers. We can write the
Addition Method with the same name having different parameters, the
concerned method will be called according to parameters.
Inheritance:

The capability of a class to derive properties and characteristics from another


class is called Inheritance. Inheritance is one of the most important features of
Object-Oriented Programming.
 Sub Class: The class that inherits properties from another class is
called Sub class or Derived Class.
 Super Class:The class whose properties are inherited by sub class is
called Base Class or Super class.
 Reusability: Inheritance supports the concept of “reusability”, i.e.
when we want to create a new class and there is already a class that
includes some of the code that we want, we can derive our new class
from the existing class. By doing this, we are reusing the fields and
methods of the existing class.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.

 C++ Classes/Objects
C++ is an object-oriented programming language.

Everything in C++ is associated with classes and objects, along with its
attributes and methods. For example: in real life, a car is an object. The car
has attributes, such as weight and color, and methods, such as drive and brake.

Attributes and methods are basically variables and functions that belongs to
the class. These are often referred to as "class members".
A class is a user-defined data type that we can use in our program, and it works
as an object constructor, or a "blueprint" for creating objects.

Create a Class

To create a class, use the class keyword:

Example

Create a class called "MyClass":


class MyClass
{ // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

 The class keyword is used to create a class called MyClass.


 The public keyword is an access specifier, which specifies that members
(attributes and methods) of the class are accessible from outside the class.
You will learn more about access specifiers later.
 Inside the class, there is an integer variable myNum and a string
variable myString. When variables are declared within a class, they are
called attributes.
 At last, end the class definition with a semicolon ;.

Create an Object

In C++, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.

To create an object of MyClass, specify the class name, followed by the object
name.

To access the class attributes (myNum and myString), use the dot syntax (.) on
the object:
Example

Create an object called "myObj" and access the attributes:

class MyClass { // The class


public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};

int main() {
MyClass myObj; // Create an object of MyClass

// Access attributes and set values


myObj.myNum = 15;
myObj.myString = "Some text";

// Print attribute values


cout << myObj.myNum << "\n";
cout << myObj.myString;
return 0;
}
Multiple Objects

You can create multiple objects of one class:

Example
// Create a Car class with some attributes
class Car {
public:
string brand;
string model;
int year;
};

int main() {
// Create an object of Car
Car carObj1;
carObj1.brand = "BMW";
carObj1.model = "X5";
carObj1.year = 1999;

// Create another object of Car


Car carObj2;
carObj2.brand = "Ford";
carObj2.model = "Mustang";
carObj2.year = 1969;

// Print attribute values


cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}
 Data members and Member functions in C++
"Data Member" and "Member Functions" are the new names/terms for the
members of a class, which are introduced in C++ programming language.

The variables which are declared in any class by using any fundamental data
types (like int, char, float etc) or derived data type (like class, structure, pointer
etc.) are known as Data Members. And the functions which are declared either
in private section of public section are known as Member functions.

There are two types of data members/member functions in C++:

1. Private members
2. Public members

1) Private members
The members which are declared in private section of the class (using private
access modifier) are known as private members. Private members can also be
accessible within the same class in which they are declared.

2) Public members

The members which are declared in public section of the class (using public
access modifier) are known as public members. Public members can access
within the class and outside of the class by using the object name of the class in
which they are declared.

Consider the example:

class Test
{
private:
int a;
float b;
char *name;

void getA() { a=10; }


...;

public:
int count;
void getB() { b=20; }

...;
};

Here, a, b, and name are the private data members and count is a public data
member. While, getA() is a private member function and getB() is public
member functions.

 Structures in C++
C/C++ arrays allow you to define variables that combine several data items of
the same kind, but structure is another user defined data type which allows you
to combine data items of different kinds.

Structures are used to represent a record, suppose you want to keep track of
your books in a library. You might want to track the following attributes about
each book −
 Title
 Author
 Subject
 Book ID

Defining a Structure
To define a structure, you must use the struct statement. The struct statement
defines a new data type, with more than one member, for your program. The
format of the struct statement is this –

struct [structure tag] {


member definition;
member definition;
...
member definition;
} [one or more structure variables];

The structure tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the structure's definition, before the final semicolon, you can specify one
or more structure variables but it is optional. Here is the way you would declare
the Book structure –

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
} book;

Accessing Structure Members

To access any member of a structure, we use the member access operator (.).
The member access operator is coded as a period between the structure variable
name and the structure member that we wish to access. You would
use struct keyword to define variables of structure type. Following is the
example to explain usage of structure −

#include <iostream>
#include <cstring>

using namespace std;

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


cout << "Book 1 title : " << Book1.title <<endl;
cout << "Book 1 author : " << Book1.author <<endl;
cout << "Book 1 subject : " << Book1.subject <<endl;
cout << "Book 1 id : " << Book1.book_id <<endl;

// Print Book2 info


cout << "Book 2 title : " << Book2.title <<endl;
cout << "Book 2 author : " << Book2.author <<endl;
cout << "Book 2 subject : " << Book2.subject <<endl;
cout << "Book 2 id : " << Book2.book_id <<endl;

return 0;
}
When the above code is compiled and executed, it produces the following result

Book 1 title : Learn C++ Programming
Book 1 author : Chand Miyan
Book 1 subject : C++ Programming
Book 1 id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Yakit Singha
Book 2 subject : Telecom
Book 2 id : 6495700

Structures as Function Arguments

You can pass a structure as a function argument in very similar way as you pass
any other variable or pointer. You would access structure variables in the
similar way as you have accessed in the above example −

#include <iostream>
#include <cstring>

using namespace std;


void printBook( struct Books book );

struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};

int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info


printBook( Book1 );

// Print Book2 info


printBook( Book2 );
return 0;
}
void printBook( struct Books book ) {
cout << "Book title : " << book.title <<endl;
cout << "Book author : " << book.author <<endl;
cout << "Book subject : " << book.subject <<endl;
cout << "Book id : " << book.book_id <<endl;
}
When the above code is compiled and executed, it produces the following result −
Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700

Pointers to Structures

You can define pointers to structures in very similar way as you define pointer
to any other variable as follows −
struct Books *struct_pointer;
Now, you can store the address of a structure variable in the above defined
pointer variable. To find the address of a structure variable, place the & operator
before the structure's name as follows −
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must
use the -> operator as follows –
struct_pointer->title;
Let us re-write above example using structure pointer, hope this will be easy for
you to understand the concept –

#include <iostream>
#include <cstring>

using namespace std;


void printBook( struct Books *book );
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
int main() {
struct Books Book1; // Declare Book1 of type Book
struct Books Book2; // Declare Book2 of type Book

// Book 1 specification
strcpy( Book1.title, "Learn C++ Programming");
strcpy( Book1.author, "Chand Miyan");
strcpy( Book1.subject, "C++ Programming");
Book1.book_id = 6495407;

// Book 2 specification
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Yakit Singha");
strcpy( Book2.subject, "Telecom");
Book2.book_id = 6495700;

// Print Book1 info, passing address of structure


printBook( &Book1 );

// Print Book1 info, passing address of structure


printBook( &Book2 );

return 0;
}

// This function accept pointer to structure as parameter.


void printBook( struct Books *book ) {
cout << "Book title : " << book->title <<endl;
cout << "Book author : " << book->author <<endl;
cout << "Book subject : " << book->subject <<endl;
cout << "Book id : " << book->book_id <<endl;
}
When the above code is compiled and executed, it produces the following result

Book title : Learn C++ Programming
Book author : Chand Miyan
Book subject : C++ Programming
Book id : 6495407
Book title : Telecom Billing
Book author : Yakit Singha
Book subject : Telecom
Book id : 6495700

Introduction to Access specifiers in C++

Access specifiers in C++ are basically used in OOPs concepts. In classes, we

start their use, they are mainly used in inheritance. They set the range for the

usage of the variable and the functions of a particular class. Access specifiers

are used for data hiding purposes also.

What is Access Specifiers in C++?


Here we will discuss some basic concept of access specifier in C++ that you

should know:

 The access specifiers used in C++ are Private, Protected and Public. The

data members and member functions of a class declared as public are

available to everyone and other classes can also access them. The public

members of a class are accessible from everywhere in the program using

the dot operator (.) which is called a direct member access operator along

with the object of the same class.

 The data members and member functions of a class declared as private

are accessible only by the inside functions of the class and are restricted
to be accessed directly by any object or function outside the class. The

private data members of a class can be accessed using the member

functions of the class or the friend functions.

 Protected access modifier is similar to that of private access modifiers,

the difference is that the class member declared as Protected cannot be

accessed outside the class however they are accessible by any derived

class or subclass of that class.

 The main difference between private and protected is that

protected inheritance allows continued access to base class members

whereas private inheritance prohibits the access of those members.

How Does Access Specifiers Work in C++?


The accessibility of access specifiers in classes during inheritance is shown in

Table.

Working of access specifiers in inheritance is as discussed below:


1. Private

While creating a class using access specifier as private, the base class’ public
and protected data members become the derived class’ private member and base
class’ private member stays private. Hence, the members of the base class can
be used only inside the derived class but are inaccessible through the object
created for the derived class. The other way to access them is to create a
function in the derived class. The below figure depicts the inheritance of data
members of the base class when the access mode of the derived class is private.

// private access specifier.cpp


#include <iostream>
using namespace std;

class base
{
private:
int x;

protected:
int y;

public:
int z;

base() //constructor to initialize data members


{
x = 1;
y = 2;
z = 3;
}
};

class derive: private base


{
//y and z becomes private members of class derive and x remains private
public:
void showdata()
{
cout << "x is not accessible" << endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};
int main()
{
derive a; //object of derived class
a.showdata();
//a.x = 1; not valid : private member can't be accessed outside of class
//a.y = 2; not valid : y is now private member of derived class
//a.z = 3; not valid : z is also now a private member of derived class
return 0;
} //end of program

Output
x is not accessible
value of y is 2
value of z is 3

2. Protected

In derived class, when protected access specifier is used, the public

and protected data members of the base class becomes the derived class’

protected member and base class’ private member are not accessible. Hence, the

members of the base class can be used only inside the derived class as protected

members. The below figure depicts the inheritance of data members of the base

class when the access mode of the derived class is protected.

// protected access specifier.cpp


#include <iostream>
using namespace std;

class base
{
private:
int x;

protected:
int y;

public:
int z;
base() //constructor to initialize data members
{
x = 1;
y = 2;
z = 3;
}
};

class derive: protected base


{
//y and z becomes protected members of class derive
public:
void showdata()
{
cout << "x is not accessible" << endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};
int main()
{
derive a; //object of derived class
a.showdata();
//a.x = 1; not valid : private member can't be accessed outside of class
//a.y = 2; not valid : y is now private member of derived class
//a.z = 3; not valid : z is also now a private member of derived class
return 0;
} //end of program

Output
x is not accessible
value of y is 2
value of z is 3

3. Public

While derived class is created, if public access specifier is used, the public data

members of the base class become the public member of the derived class and
protected members become the protected in the derived class but the private

members of the base class are inaccessible. The following figure depicts the

inheritance of data members of the base class when the access mode of the

derived class is public.

// public access specifier.cpp


#include <iostream>
using namespace std;

class base
{
private:
int x;

protected:
int y;

public:
int z;

base() //constructor to initialize data members


{
x = 1;
y = 2;
z = 3;
}
};

class derive: public base


{
//y becomes protected and z becomes public members of class derive
public:
void showdata()
{
cout << "x is not accessible" << endl;
cout << "value of y is " << y << endl;
cout << "value of z is " << z << endl;
}
};
int main()
{
derive a; //object of derived class
a.showdata();
//a.x = 1; not valid : private member can't be accessed outside of class
//a.y = 2; not valid : y is now private member of derived class
//a.z = 3; not valid : z is also now a private member of derived class
return 0;
} //end of program

Output
x is not accessible
value of y is 2
value of z is 3

The functions associated with a class are called member functions of that class.

Member functions must be declared inside the class but they can be defined
either inside the class or outside the class.

 Different ways of defining member functions of a class


There are two ways in which the member functions can be defined :

 Inside the class definition


 Outside the class definition

C++ class and functions: Inside the class definition


As the name suggests, here the functions are defined inside the class.

Functions defined inside the class are treated as inline functions automatically if
the function definition doesn’t contain looping statements or complex multiple
line operations.

Example

#include <iostream>
using namespace std;
class car
{
private:
int car_number;
char car_model[10];
public:
void getdata()
{
cout<<"Enter car number: "; cin>>car_number;
cout<<"\n Enter car model: "; cin>>car_model;
}
void showdata()
{
cout<<"Car number is "<<car_number;
cout<<"\n Car model is "<<car_model;
}
};
// main function starts
int main()
{
car c1;
c1.getdata();
c1.showdata();
return 0;
}
Output

Enter car number : 9999

Enter car model : Sedan

Car number is 9999

Car model is Sedan

Here in above program getdata() and showdata() are the member function
defined inside the class.

C++ class and functions: Outside the class definition


As the name suggests, here the functions are defined outside the class however
they are declared inside the class.

Functions should be declared inside the class to bound it to the class and
indicate it as it’s member but they can be defined outside of the class.
To define a function outside of a class, scope resolution operator :: is used.

Syntax for declaring function outside of class


class class_name
{
........
........
public:
return_type function_name (args); //function declaration
};
//function definition outside class
return_type class_name :: function_name (args)
{
...........; // function definition
}
Example

#include <iostream>
using namespace std;
class car
{
private:
int car_number;
char car_model[10];
public:
void getdata(); //function declaration
void showdata();
};
// function definition
void car::getdata()
{
cout<<"Enter car number: "; cin>>car_number;
cout<<"\n Enter car model: "; cin>>car_model;
}
void car::showdata()
{
cout<<"Car number is "<<car_number;
cout<<"\n Car model is "<<car_model;
}
// main function starts
int main()
{
car c1;
c1.getdata();
c1.showdata();
return 0;
}
Output

Enter car number : 9999

Enter car model : Sedan

Car number is 9999

Car model is Sedan

Here is this program, the functions showdata() and getdata() are declared inside
the class and defined outside the class. This is achieved by using scope
resolution operator ::.

 C++ Array of Objects


You can store objects of user defined datatype in a C++ Array.
To store objects of user defined datatype in an array, you can declare an array of
the specific type and initialize the array just like an array of ints.

C++ Array of Objects – Declare and Initialize Separately


In the following example, we shall declare an array of type Student, with size of
five. Student is a class that we defined in the program. Then we shall assign
objects using index of array.
C++ Program
#include <iostream>
using namespace std;

class Student {
public:
string name;
int rollno;

Student() {}

Student(string x, int y) {
name = x;
rollno = y;
}

void printDetails() {
cout << rollno << " - " << name << endl;
}
};

int main() {
//declare array with specific size
Student students[5];

//assign objects
students[0] = Student("Ram", 5);
students[1] = Student("Alex", 1);
students[2] = Student("Lesha", 4);
students[3] = Student("Emily", 3);
students[4] = Student("Anita", 2);

for(int i=0; i < 5; i++) {


students[i].printDetails();
}
}
Output
5 – Ram
1 - Alex
4 - Lesha
3 - Emily
2 – Anita

C++ Array of Objects – Declare and Initialize in a Single Line


In the following example, we shall declare an array of type Student, and
initialize the array with objects of Student type in a single line.
C++ Program
#include <iostream>
using namespace std;

class Student {
public:
string name;
int rollno;

Student() {}

Student(string x, int y) {
name = x;
rollno = y;
}

void printDetails() {
cout << rollno << " - " << name << endl;
}
};

int main() {
//declare array with specific size
Student students[] = {Student("Ram", 5), Student("Lesha", 4), Student("Anita", 2)};

for(int i=0; i < 3; i++) {


students[i].printDetails();
}
}
Output
5 - Ram
4 - Lesha
2 – Anita

You might also like