Classes Introduction
In C++ we use classes to define our own abstract data types. By defining types that mirror concepts in the problems we are trying to solve, we can make our programs easier to write, debug, and modify.
Classes are the most important feature in C++. Early versions of the language were named “C with Classes,” emphasizing the central role of the class facility. As the language evolved, support for building classes increased. A primary goal of the language design has been to provide features that allow programmers to define their own types that are as easy and intuitive to use as the built-in types. these tutorials presents many of the basic features of classes.
Class Definitions and Declarations
A Class is a collection of member data and member functions encapsulated within a single entity. Example :
#include <iostream> using namespace std; void initializeCar(); void fourthGear(); class Car { int top_speed; // private by default int wheels; // private by default public: // public declaration void initializeCar() { top_speed = 140; wheels = 4; cout << "Top Speed " << top_speed; cout << "\nWheels " << wheels; } int firstGear() { cout << "Below 10 Speed"; return 0; } int secondGear() { cout << "speed 10 - 20"; return 0; } int thirdGear() { cout << "Speed 20-30"; return 0; } void fourthGear() { cout << "above 30"; } }; int main() { Car mycar; // making object of class cout << "speed in fourth gear is "; mycar.fourthGear(); // calling member function getchar(); return 0; }
Output
speed in fourth gear is above 30