What is a class? Explain in reference of C++.

A class is also a user defined data type very similar to structure but some more advanced features.

A class is used to classify different entities of some project. The class is the basis of one of the most important programming paradigms called OOPs.

A class can have different kinds of hetrogeneous members

  • data members or fields
  • methods
Data members are very similar to fields about an entity very similar to structures.
Methods are special functions created inside the class.

Methods can be of two types
  • Special methods
  • General methods
Special methods again can be of four types
  • Constructor
  • Destructor
  • Setter
  • Getter
Constructor is special method inside a class having special features
  • Same name as class name
  • No return type
  • Used to initailize the data members of an instance
  • Constructors can be overloaded
Destructor is the special method inside a class having special features
  • Same name as class name preceded by tild sign (~)
  • It get called automatically when an instance goes out of scope
  • Cannot be overloaded
Setter is the special method inside a class used to update the value inside some data member of the instance. Setters are preceded by set.

Getters are also special method inside a class used to return value in some data member of an instance. Getters are peceded by get.

Example
Create a class Customer having fields as cid, name and balance. Create a constructor to initialize a customer account. Create a setter to update the name. Create getter of all three data members. Create a method deposit() to deposit some amount. Create a method withdraw() to withdraw some amount.

Create an entry point to create an instance of Customer class with sample data as cid=123, name=Rohit Kumar, opening amount=5000
Deposit 6000 more and Withdraw 1500

Show the balance of the customer in following format
  Balance of <name> having customer id <cid> is <balance>.

Solution
Note: 
Use this pointer to access the data members of current instance inside a class, if required


#include <iostream>
#include <string.h>
using namespace std;
class Customer
{
private:
int cid;
char name[51];
double balance;
public:
Customer(int cid, char *name, double openingamount)
{
this->cid=cid;
strcpy(this->name,name);
balance=openingamount;
}
void setName(char *name)
{
strcpy(this->name,name);
}
int getCid()
{
return cid;
}
char *getName()
{
return name;
}
double getBalance()
{
return balance;
}
void deposit(double amount)
{
balance+=amount;
}
void withdraw(double amount)
{
balance-=amount;
}
};
main()
{
Customer c(123,"Rohit Kumar",5000);
c.deposit(6000);
c.withdraw(1500);
cout <<"Balance of "<<c.getName() << " having customer id "<< c.getCid()<<" is " << c.getBalance();
}

Output
Balance of Rohit Kumar having customer id 123 is 9500

Comments

Popular posts from this blog

What is template?

Can we access private members of an instance?

What are wrapper classes in Java?