Classes and objects in c++
Class
- A class is a template that defines the form of an object.
- A class specifies both code and data.
- C++ uses a class specification to construct objects.
- Objects are instances of a class.
- Thus, a class is essentially a set of plans that specify how to build an object.
- A class can contain private as well as public members. By default, all items defined in a class are private.
- When you define a class, you declare the data that it contains and the code that operates on that data.
- While very simple classes might contain only code or only data, most real-world classes contain both.
- Data is contained in instance variables defined by the class, and code is contained in functions. The code and data that constitute a class are called members of the class.
Syntax
class-name
{
private data and functions
public:
public data and functions
} object-list;
Defining the Class
class smallobj //define a class
{
private:
int somedata; //class data
public:
void setdata(int d) //member function to set data
{
somedata = d;
}
void showdata() //member function to display data
{
cout << “
Data is “ << somedata;
}
};
Object
- An Object is a bit of self-contained Code and Data.
- A key aspect of the Object approach is to break the problem into smaller understandable parts (divide and conquer).
- Objects have boundaries that allow us to ignore un-needed detail.
- We have been using objects all along: String Objects, Integer Objects, Dictionary Objects, List Objects.
Example
// A program that uses the Vehicle class.
#include
using namespace std;
// Declare the Vehicle class.
class Vehicle
{
public:
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
};
int main()
{
Vehicle minivan; // create a Vehicle object
int range;
// Assign values to fields in minivan.
minivan.passengers = 7;
minivan.fuelcap = 16;
minivan.mpg = 21;
// Compute the range assuming a full tank of gas.
range = minivan.fuelcap * minivan.mpg;
cout << "Minivan can carry " << minivan.passengers << " with a range of " << range << "";
return 0;
}
Output
Minivan can carry 7 with a range of 336