Classes and objects in c++
- 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.
private data and functions
public data and functions
Defining the Class
class smallobj //define a class
int somedata; //class data
void setdata(int d) //member function to set data
somedata = d;
void showdata() //member function to display data
cout << “
Data is “ << somedata;
- 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.
// A program that uses the Vehicle class.
using namespace std;
// Declare the Vehicle class.
int passengers; // number of passengers
int fuelcap; // fuel capacity in gallons
int mpg; // fuel consumption in miles per gallon
Vehicle minivan; // create a Vehicle object
// 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 << "";
Minivan can carry 7 with a range of 336