Classes
Contents
Introduction
Procedural vs Object oriented ProgrammingThe feature of classes is what sets "C++" apart from the "C" language that it evolved from. Classes allow "C++" to let coding be done in an object oriented fashion. Most of the modern languages support object oriented programming. It wasn't always like that. For a long time programming was done in procedural languages like "C", "Fortran" and "Pascal". Object oriented programming lets us create classes where we can place our data variables and member functions. Thinking of the problem domain in terms of objects allows us to organize and reuse our code in a more natural way than procedural programming. This might not make a difference when a few hundred lines of code are involved but becomes important when the program is huge with number of lines going into thousands. Almost all of modern programming utilizes the object oriented programming approach.
A class defines a type. It consists of properties and methods. We can organize our code in terms of the problem domain.
File: c1.cpp
#include <string> #include <iostream> using namespace std ; class Person { string firstName ; string lastName ; int age ; void print() { cout << "Name:" << firstName << " " << lastName << " Age: " << age << endl ; } }; int main() { Person personObj ; return 0 ; }The above defines a class with the keyword "class" . In this class we place the properties such as "firstName" and "lastName" and we also have a method that operates on the properties. We can then use the class as a type to create our objects.
Person personObj ; This is very similar to defining variables with the types such as : int x1 ; A variable "personObj" is created on the stack.