0% found this document useful (0 votes)
11 views

Class and Object Cpp New

Uploaded by

tanmaytati99
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)
11 views

Class and Object Cpp New

Uploaded by

tanmaytati99
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/ 33

Alphabet Computer Education, Narayangaon, 9960552002

1. Classes and Objects

Class: A class in C++ is the building block that leads to Object-Oriented programming. 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 C++ class is like a blueprint
for an object

In C++, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc. In
other words, object is an entity that has state and behavior. Here, state means data and
behavior means functionality. Object is a runtime entity, it is created at runtime. Object is
an instance of a class.

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)
};

Create a Class with object

class Abc

private:

int x;

public:

void display()

{
Alphabet Computer Education, Narayangaon, 9960552002

// some statement

};

int main()

Abc obj; // Object of class Abc created

Access Control in C++

Now before studying how to define class and its objects, lets first quickly learn what are
access modifiers.

Access modifiers in C++ class defines the access control rules. C++ has 3 new keywords
introduced, namely,

1. public
2. private
3. protected

These access modifiers are used to set boundaries for availability of members of class be it
data members or member functions

Public Access Modifier in C++

Public, means all the class members declared under public will be available to everyone. The
data members and member functions declared public can be accessed by other classes too.

class PublicAccess

// public access modifier

public:
Alphabet Computer Education, Narayangaon, 9960552002

int x; // Data Member Declaration

void display(); // Member Function decaration

Private Access Modifier in C++

Private keyword, means that no one can access the class members declared private, outside
that class. If someone tries to access the private members of a class, they will get a compile
time error. By default class variables and member functions are private.

class PrivateAccess

// private access modifier

private:

int x; // Data Member Declaration

void display(); // Member Function decaration

Protected Access Modifier in C++

Protected, is the last access specifier, and it is similar to private, it makes class member
inaccessible outside the class. But they can be accessed by any subclass of that class. (If
class A is inherited by class B, then class B is subclass of class A. We will learn about
inheritance later.)

class ProtectedAccess

// protected access modifier

protected:

int x; // Data Member Declaration


Alphabet Computer Education, Narayangaon, 9960552002

void display(); // Member Function decaration

Defining Class and Creating Objects for student inside class definition

#include<iostream.h>

#include<conio.h>

class student

private:

char name[20],regd[10],branch[10];

int sem;

public:

void input()

cout<<"Enter Name:";

cin>>name;

cout<<"Enter Regdno.:";

cin>>regd;

cout<<"Enter Branch:";

cin>>branch;

cout<<"Enter Sem:";

cin>>sem;

}
Alphabet Computer Education, Narayangaon, 9960552002

void display()

cout<<"\nName:"<<name;

cout<<"\nRegdno.:"<<regd;

cout<<"\nBranch:"<<branch;

cout<<"\nSem:"<<sem;

};

void main()

student s;

s.input();

s.display();

getch();

Sample Input
Enter Name:Bikash
Enter Regdno.:123
Enter Branch:CS
Enter Sem:5
Sample Output
Name:Bikash
Regdno.:123
Branch:CS
Sem:5

Defining Class and Creating Objects for student outside class definition
Alphabet Computer Education, Narayangaon, 9960552002

#include<iostream.h>

#include<conio.h>

class student

private:

char name[20],regd[10],branch[10];

int sem;

public:

void input();

void display();

};

void student::input()

cout<<"Enter Name:";

cin>>name;

cout<<"Enter Regdno.:";

cin>>regd;

cout<<"Enter Branch:";

cin>>branch;

cout<<"Enter Sem:";

cin>>sem;

void student::display()
Alphabet Computer Education, Narayangaon, 9960552002

cout<<"\nName:"<<name;

cout<<"\nRegdno.:"<<regd;

cout<<"\nBranch:"<<branch;

cout<<"\nSem:"<<sem;

int main()

student s;

s.input();

s.display();

getch();

Q. Define a class to represent a bank account. Include the following members:

Data members:
1) Name of the depositor
2) Account number
3) Type of account
4) Balance amount in the account.

Member functions:
1) To assign initial values
2) To deposit an amount
3) To withdraw an amount after checking the balance
4) To display name and balance.
Alphabet Computer Education, Narayangaon, 9960552002

Write a main program to test the program.

#include<iostream.h>

#include<stdio.h>

#include<string.h>

#include<conio.h>

class bank

int acno;

char name[100], acctype[100];

float balance;

public:

void input()

cout<<"\n Enter Account No";

cin>>acno;

cout<<"\n Enter Customer Name";

cin>>name;

cout<<"\n Enter Account Type";

cin>>acctype;

cout<<"\n Enter Account Balance";

cin>>balance;
Alphabet Computer Education, Narayangaon, 9960552002

void deposit();

void withdraw();

void display();

};

void bank::deposit()

int damt1;

cout<<"\n Enter Deposit Amount = ";

cin>>damt1;

balance+=damt1;

void bank::withdraw()

int wamt1;

cout<<"\n Enter Withdraw Amount = ";

cin>>wamt1;

if(wamt1>balance)

cout<<"\n Cannot Withdraw Amount";

balance-=wamt1;

void bank::display()

{
Alphabet Computer Education, Narayangaon, 9960552002

cout<<"\n ----------------------";

cout<<"\n Accout No. : "<<acno;

cout<<"\n Customer Name : "<<name;

cout<<"\n Account Type : "<<acctype;

cout<<"\n Account Balance : "<<balance;

int main()

bank b1;

clrscr();

b1.input();

b1.deposit();

b1.withdraw();

b1.display();

getch();

return 0;

Accessing Public Data Members

Following is an example to show you how to initialize and use the public data members using
the dot (.) operator and the respective object of class.

#include<iostream.h>
Alphabet Computer Education, Narayangaon, 9960552002

#include<conio.h>

class Student

public:

int rollno;

};

int main()

Student A;

Student B;

A.rollno=1;

B.rollno=2;

cout <<" Roll no of A is: << A.rollno<<endl;

cout <<" Roll no of B is: << B.rollno;

Roll no of A is: 1

Roll no of B is: 2

Accessing Private Data Members

To access, use and initialize the private data member you need to create getter and setter
functions, to get and set the value of the data member.

The setter function will set the value passed as argument to the private data member, and
the getter function will return the value of the private data member to be used. Both
getter and setter function must be defined public.
Alphabet Computer Education, Narayangaon, 9960552002

#include<iostream.h>

#include<conio.h>

class Student

private: // private data member

int rollno;

public: // public function to get value of rollno - getter

int getRollno()

return rollno;

void setRollno(int i)

rollno=i;

};

int main()

Student A;

A.rollono=1; //Compile time error

cout<< A.rollno; //Compile time error


Alphabet Computer Education, Narayangaon, 9960552002

A.setRollno(26);

cout<< “roll no is= <<A.getRollno();

Write a C++ program to implement a class called Circle that has private
member variables for radius. Include member functions to calculate the circle's
area

#include <iostream.h>

#include <conio.h>

#include <math.h>

const double PI = 3.14159;

class Circle {

private:

double radius;

public:

void input(double rad)

radius=rad;

}
Alphabet Computer Education, Narayangaon, 9960552002

double calculateArea()

return PI * pow(radius, 2);

};

int main()

double radius;

cout << "Input the radius of the circle: ";

cin >> radius;

Circle c;

clrscr();

c.input(radius);

double area = c.calculateArea();

cout << "Area: " << area << endl;

getch();

return 0;

Example for Array of object


Alphabet Computer Education, Narayangaon, 9960552002

#include<iostream.h>

#include<conio.h>

class Employee

int Id;

char Name[25];

int Age;

long Salary;

public:

void GetData() //Statement 1 : Defining GetData()

cout<<"\n\tEnter Employee Id : ";

cin>>Id;

cout<<"\n\tEnter Employee Name : ";

cin>>Name;

cout<<"\n\tEnter Employee Age : ";

cin>>Age;

cout<<"\n\tEnter Employee Salary : ";

cin>>Salary;

}
Alphabet Computer Education, Narayangaon, 9960552002

void PutData() //Statement 2 : Defining PutData()

cout<<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary;

};

void main()

int i;

Employee E[3];

clrscr();

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

cout<<"\nEnter details of "<<i+1<<" Employee";

E[i].GetData();

cout<<"\nDetails of Employees";

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

E[i].PutData();

getch();

Output :

Enter details of 1 Employee


Alphabet Computer Education, Narayangaon, 9960552002

Enter Employee Id : 101

Enter Employee Name : Suresh

Enter Employee Age : 29

Enter Employee Salary : 45000

Enter details of 2 Employee

Enter Employee Id : 102

Enter Employee Name : Mukesh

Enter Employee Age : 31

Enter Employee Salary : 51000

Enter details of 3 Employee

Enter Employee Id : 103

Enter Employee Name : Ramesh

Enter Employee Age : 28

Enter Employee Salary : 47000

Details of Employees

101 Suresh 29 45000

102 Mukesh 31 51000

103 Ramesh 28 47000

Types of Class Member Functions in C++


Alphabet Computer Education, Narayangaon, 9960552002

We already know what member functions are, what they do, how to define member function
and how to call them using class objects. Now let’s learn about some special member
functions which can be defined in C++ classes. Following are the different types of Member
functions:

Simple functions

Static functions

Const functions

Inline functions

Friend functions

Simple Member functions in C++

These are the basic member function, which dont have any special keyword like static etc
as prefix. All the general member functions, which are of below given form, are termed as
simple and basic member functions.

return_type functionName(parameter_list)

function body;

Function with no argument and no return value.

#include <iostream>

#include<conio.h>

class Employee

int id;

float salary;
Alphabet Computer Education, Narayangaon, 9960552002

public:

void insert()

cout<<"\n\tEnter Employee Id : ";

cin>>Id;

cout<<"\n\tEnter Employee Salary : ";

cin>>Salary;

void display()

cout<< Employee Id is = <<id<<endl;

cout<< Employee Salary is = <<salary<<endl;

};

int main(void)

Employee e1;

clrscr();

e1.insert();

e1.display();

getch();

return 0;

Function with no argument but return value.


Alphabet Computer Education, Narayangaon, 9960552002

#include <iostream>

#include<conio.h>

class Employee

int id;

float salary;

public:

void insert()

cout<<"\n\tEnter Employee Id : ";

cin>>Id;

cout<<"\n\tEnter Employee Salary : ";

cin>>salary;

int returnid()

return id;

float returnsalary()

return salary;

};

int main(void)
Alphabet Computer Education, Narayangaon, 9960552002

Employee e1;

clrscr();

e1.insert();

cout<< Employee Id is = <<e1. returnid()<<endl;

cout<< Employee Salary is = <<e1.returnsalary()<<endl;

getch();

return 0;

Function with argument but no return value.

#include <iostream>

#include<conio.h>

class Employee

public:

int id;

float salary;

void insert(int i, float s)

id = i;

salary = s;

void display()

cout<< Employee Id is = <<id<<endl;


Alphabet Computer Education, Narayangaon, 9960552002

cout<< Employee Salary is = <<salary<<endl;

};

int main(void)

Employee e1;

clrscr();

e1.insert(201, 990000);

e1.display();

getch();

return 0;

Function with argument and return value.

#include <iostream>

#include<conio.h>

class Employee

public:

int id;

float salary;

void insert(int i, float s)

id = i;

salary = s;

}
Alphabet Computer Education, Narayangaon, 9960552002

int returnid()

return id;

float returnsalary()

return salary;

};

int main(void)

Employee e1;

clrscr();

e1.insert(201, 990000);

cout<< Employee Id is = <<e1. returnid()<<endl;

cout<< Employee Salary is = <<e1.returnsalary()<<endl;

getch();

return 0;

Static Member functions in C++


Static is something that holds its position. Static is a keyword which can be used with data
members as well as the member functions. A function is made static by using static keyword
Alphabet Computer Education, Narayangaon, 9960552002

with function name. These functions work for the class as whole rather than for a particular
object of a class.

It can be called using the object and the direct member access But, its more typical to call
a static member function by itself, using class name and scope resolution :: operator.

#include <iostream>

#include<conio.h>

class X

public:

static void f()

cout<<”I am static function”;

};

int main()

X::f();

These functions cannot access ordinary data members and member functions, but
only static data members and static member functions can be called inside them.

Const Member functions in C++


Const keyword makes variables constant, that means once defined, there values can't be
changed. When used with member function, such member functions can never modify the
object or its related data members.
Alphabet Computer Education, Narayangaon, 9960552002

// basic syntax of const Member Function

void fun() const

// statement

C++ program to demonstrate that data members can be


updated in a member function that is not constant.

#include <iostream>

#include<conio.h>

class Demo {

int x;

public:

void set_data(int a)

x = a;

int get_data()

++x;

return x;
Alphabet Computer Education, Narayangaon, 9960552002

};

main()

Demo d;

clrscr();

d.set_data(10);

cout << d.get_data();

getch();

return 0;

Output

11

C++ program to demonstrate that data cannot be updated


in a Constant member function

#include <iostream>

#include<conio.h>

class Demo {

int x;

public:
Alphabet Computer Education, Narayangaon, 9960552002

void set_data(int a)

x = a;

int get_data() const

// Error while attempting to modify the data

// member

++x;

return x;

};

main()

Demo d;

clrscr();

d.set_data(10);

cout << endl << d.get_data();

getch();

return 0;

Output

./Solution.cpp: In member function 'int Demo::get_data() const':

./Solution.cpp:17:11: error: increment of member 'Demo::x' in read-only object


Alphabet Computer Education, Narayangaon, 9960552002

++x;

Constant member function defined outside the class

#include <iostream>

#include<conio.h>

class Demo

int x;

public:

void set_data(int);

int get_data() const;

};

void Demo::set_data(int a)

x = a;

int Demo::get_data() const

return x;

}
Alphabet Computer Education, Narayangaon, 9960552002

main()

Demo d;

d.set_data(10);

cout << d.get_data();

getch();

return 0;

Output

10

Inline functions in C++


All the member functions defined inside the class definition are by default declared as Inline.

One of the key features of C++ is the inline function. Therefore, let's first examine the
utilization of inline functions and their intended application. If make a function is inline,
then the compiler replaces the function calling location with the definition of the inline
function at compile time.

Any changes made to an inline function will require the inline function to be recompiled
again because the compiler would need to replace all the code with a new code; otherwise,
it will execute the old functionality.

The syntax for defining the function inline is:

inline return-type function-name(parameters)

// function code

#include<iostream.h>
Alphabet Computer Education, Narayangaon, 9960552002

#include<conio.h>

inline int cube(int s)

return s*s*s;

int main()

cout << "The cube of 3 is: " << cube(3) << "\n";

return 0;

Output: The cube of 3 is: 27

class operation

int a,b,add,sub,mul;

float div;

public:

void get();

void sum();

void difference();

void product();

void division();

};
Alphabet Computer Education, Narayangaon, 9960552002

inline void operation :: get()

cout << "Enter first value:";

cin >> a;

cout << "Enter second value:";

cin >> b;

inline void operation :: sum()

add = a+b;

cout << "Addition of two numbers: " << add<< "\n";

inline void operation :: difference()

sub = a-b;

cout << "Difference of two numbers: " << sub<< "\n";

inline void operation :: product()

mul = a*b;

cout << "Product of two numbers: " << mul<< "\n";


Alphabet Computer Education, Narayangaon, 9960552002

inline void operation ::division()

div=a/b;

cout<<"Division of two numbers: "<<div <<"\n" ;

int main()

cout << "Program using inline function\n";

operation s;

s.get();

s.sum();

s.difference();

s.product();

s.division();

return 0;

Output:

Enter first value: 45

Enter second value: 15

Addition of two numbers: 60


Alphabet Computer Education, Narayangaon, 9960552002

Difference of two numbers: 30

Product of two numbers: 675

Division of two numbers: 3

You might also like