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
The classes in C++ have 3 important access levels.
The members are accessible only by the member functions or friend functions.
These members are accessible by the member functions of the class and the classes which are derived from this class.
Accessible by any external member. Look at the sample class below.
- 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 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++.
using namespace std;
balance = 1000;
cout<<“Enter income to be deposit:”<<endl;
cout<<“balance = “<<balance<<endl;
cout<<“Enter income to withdraw:”<<endl;
cout<<“total balance is “<<balance<<endl;