• No results found

What is Class and Object in C++?

In document Object Oriented Technology (Page 26-35)

Class and Objects

Q.1. What is Class and Object in C++?

Ans.: Class:-

A class is a way to bind the data and function together in a single unit.

When we define a class , we create a new abstract data type that can be treated like other build in data type. The variables of class are called objects or instance of a class.

A class specification has two parts:

i) Class Declaration

ii) Class Function definitions

A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. A class definition must be followed either by a semicolon or a list of declarations.

For example we defined the Box data type using the keyword class as follows:

class Box {

public:

double length;

double breadth;

double height;

double getVolume(void) {

return length * breadth * height;

} };

The keyword public determines the access attributes of the members of the class that follow it. A public member can be accessed from outside the class anywhere within the scope of the class object. A class member can be defined as public, private or protected. By default members would be assumed as private. A member function of a class is a function that has its

definition or its prototype within the class definition like any other variable.

Creating Objects:-

A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types. Following statements declare two objects of class Box:

Box Box1; // Declare Box1 of type Box Box Box2;

A Class and Object Example class Box

{

public:

double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box // Member functions declaration double getVolume(void);

void setLength( double len );

void setBreadth( double bre );

void setHeight( double hei );

};

// Member functions definitions double Box::getVolume(void) {

return length * breadth * height;

}

void Box::setLength( double len ) {

length = len;

}

void Box::setBreadth( double bre ) {

breadth = bre;

}

void Box::setHeight( double hei ) {

height = hei;

}

// Main function for the program 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.setLength(6.0);

Box1.setBreadth(7.0);

Box1.setHeight(5.0);

// box 2 specification Box2.setLength(12.0);

Box2.setBreadth(13.0);

Box2.setHeight(10.0);

// volume of box 1

volume = Box1.getVolume();

cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2

volume = Box2.getVolume();

cout << "Volume of Box2 : " << volume <<endl;

return 0;

}

When the above code is compiled and executed, it produces following result:

Volume of Box1 : 210 Volume of Box2 : 1560

Q2 What do you understand by class member function?

Ans. The member functions are set of functions that are applied to objects of that class. A function as a member of a class is also called a Method. A member function is declared like any of the functions we have used so far;

it could or could not return a value.

When using functions on a class, the variables are used to hold or store values, called data, of the object, while member functions are used to perform assignments as related to the objects. One way you can control the data held by variables is to hide data from the “external world”. To achieve this, you should declare the member variables in the private section. After doing this, use the methods in the public section to help the class interact with the other objects or functions of the program.

Q3 What is an Array of Objects in C++?

Ans Arrays of variables of type "class" is known as "Array of objects". The

"identifier" used to refer the array of objects is an user defined data type.

#include <iostream.h>

const int MAX =100;

class Details {

private:

int salary;

float roll;

public:

void getname( ) {

cout << "\n Enter the Salary:";

cin >> salary;

cout << "\n Enter the roll:";

cin >> roll;

}

void putname( ) {

cout << "Employees" << salary <<

"and roll is" << roll << '\n';

} };

void main() {

Details det[MAX];

int n=0;

char ans;

do{

cout << "Enter the Employee Number::" << n+1;

det[n++].getname;

cout << "Enter another (y/n)?: " ; cin >> ans;

} while ( ans != 'n' );

for (int j=0; j<n; j++) {

cout << "\nEmployee Number is:: " << j+1;

det[j].putname( );

} }

Result:

Enter the Employee Number:: 1 Enter the Salary:20

Enter the roll:30

Enter another (y/n)?: y

Enter the Employee Number:: 2 Enter the Salary:20

Enter the roll:30

Enter another (y/n)?: n

In the above example an array of object "det" is defined using the user defined data type "Details". The class element "getname()" is used to get the input that is stored in this array of objects and putname() is used to display the information.

Q4 What is Nested classes in C++?

Ans Nested class is a class defined inside a class, that can be used within the scope of the class in which it is defined. In C++ nested classes are not given importance because of the strong and flexible usage of inheritance.

Its objects are accessed using "Nest::Display".

#include <iostream.h>

class Nest {

public:

class Display {

private:

int s;

public:

void sum( int a, int b) { s =a+b; }

void show( )

{ cout << "\nSum of a and b is:: " << s;}

};

};

void main() {

Nest::Display x;

x.sum(12, 10);

x.show();

} Result:

Sum of a and b is::22

In the above example, the nested class "Display" is given as "public" member of the class "Nest".

Q5 what is inline function in c++ ?

Ans C++ inline function is powerful concept that is commonly used with classes. If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time.

Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality.

To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function.

Following is an example which makes use of inline function

#include <iostream>

inline int Max(int x, int y) {

return (x > y)? x : y;

}

// Main function for the program main( )

{

cout << "Max (20,10): " << Max(20,10) << endl;

cout << "Max (0,200): " << Max(0,200) << endl;

cout << "Max (100,1010): " << Max(100,1010) << endl;

return 0;

}

When the above code is compiled and executed, it produces following result:

Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010

Q6 What do you mean by friend function?

Ans A friend function is used for accessing the non-public members of a class.

A class can allow non-member functions and other classes to access its own private data, by making them friends. Thus, a friend function is an ordinary function or a member of another class. The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function

must have the class to which it is declared as friend passed to it in argument.

Example to understand the friend function #include <iostream>

using namespace std;

class fri {

private:

int a,b;

public:

void test() {

a=100;

b=200;

}

friend int compute(fri e1);

//Friend Function Declaration with keyword friend and with the object of class fri to which it is friend passed to it

};

int compute(fri e1) {

//Friend Function Definition which has access to private data return int(e1.a+e1.b)-5;

}

void main() {

fri e;

e.test();

cout << "The result is:" << compute(e);

//Calling of Friend Function with object as argument.

}

Q7 What do you mean by static member function.

Ans The keyword static is used to precede the member function to make a member function static. The static member function has following properties:

1) A static function have access to only static member declared in the class.

2) A static member function can be called using the class names as : Classname : : functionname;

3) A static member function acts as global for the data member of its class without affecting the rest of the program.

Q8 What do you mean by Dynamic Memory Allocation?

Ans Allocating memory

There are two ways that memory gets allocated for data storage:

Compile Time (or static) Allocation

Memory for named variables is allocated by the compiler.

Exact size and type of storage must be known at compile time For standard array declarations, this is why the size has to be constant

Dynamic Memory Allocation

Memory allocated "on the fly" during run time

dynamically allocated space usually placed in a program segment known as the heap or the free store

Exact amount of space or number of items does not have to be known by the compiler in advance.

For dynamic memory allocation, pointers are crucial Dynamic Memory Allocation

We can dynamically allocate storage space while the program is running, but we cannot create new variable names "on the fly"

For this reason, dynamic allocation requires two steps:

a) Creating the dynamic space.

b) Storing its address in a pointer (so that the space can be accesed) To dynamically allocate memory in C++, we use the new operator.

De-allocation:

Deallocation is the "clean-up" of space being used for variables or other data storage

Compile time variables are automatically deallocated based on their known extent (this is the same as scope for "automatic"

variables)

It is the programmer's job to deallocate dynamically created space To de-allocate dynamic memory, we use the delete operator

In document Object Oriented Technology (Page 26-35)