Classes

A Class is a user defined datatype which contains the variables, properties and methods in it. A class defines the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the thing’s behaviors (the things it can do, or methods, operations or features).

  • Classes are Reusable
  • Objects are instantiated (created) from the class
  • For example, a Honda Civic is an instance of a Class Car

Access Levels

The classes in C++ have 3 important access levels.

  • Private
    The members are accessible only by the member functions or friend functions.
  • Protected
    These members are accessible by the member functions of the class and the classes which are derived from this class.
  • Public
    Accessible by any external member. Look at the sample class below.

Constructors

  • Constructors have the same name as the class.
  • Constructors do not return any values.
  • Constructors are invoked first when a class is initialized. Any initialization for the class members, memory allocations are done at the constructor.

Destructors

  • Destructors in C++ also have the same name, except for the fact that they are preceded by a ‘~’ operator.
  • The destructors are called when the object of a class goes out of scope.

Let’s have an example:

A person has a balance of $1000.He will deposit any amount in his account as well as he can deposit.Find his total balance by using classes in c++.

Code

#include<iostream>
using namespace std;
class bank
{
char name[20];
int num;
char type[20];
float balance;
int income;
public:
bank()
{
balance = 1000;
}
void deposit()
{
cout<<“Enter income to be deposit:”<<endl;
cin>>income;
balance=balance+income;
cout<<“balance = “<<balance<<endl;

}
void withdraw()
{
cout<<“Enter income to withdraw:”<<endl;
cin>>income;
balance=balance-income;
}
void display()
{
cout<<“total balance is “<<balance<<endl;
}
};
void main()
{
bank acc;
bank();
acc.deposit();
acc.withdraw();
acc.display();
getchar();
getchar();
}

Print Friendly

Share this with your friends

Leave a Reply

Your email address will not be published. Required fields are marked *