Classes and Objects
Classes and Objects are the essence of Object Oriented programming. Everything that we do in C++ (and other programming languages) is connected with these two terms.
Class is a user-defined type or data structure that is composed of 2 elements (members): data members (aka fields or attributes ) and member functions (aka methods)
Object is an instance of a class.
A car is most often used as an example. You have a car that is an object. That car has its attributes (color, max speed, weight etc.) and it also has its functions (autopilot, brake, play radio etc.).
Basically, a class serves as a blueprint for creating objects that we can use in our program (mostly for communication between those objects).
Class is defined by typing the keyword “class” and its name right after it.
The class body represents the area between braces (first and last one) and contains all of the previously mentioned attributes and functions.
We will give you an example of how a class might look like (details will be explained later):
class ClassName {
private://access specifier (public, protected, private)
//attributes of a class(aka fields)
int attribute1;
long attribute2;
char attribute3;
public:
//functions of a class (aka methods)
void function1(){}
int function2() { return attribute1; }
};//semicolon is needed
By default it is possible to:
- define objects, pointers and references to objects, and arrays of class objects
- assign values (operator =) from one object to another
- taking the address of objects (operator &)
- indirect access to objects via pointers (operator *)
- direct access to attributes and calling methods (operator .)
- indirect access to attributes and methods via pointers (operator ->)
- accessing elements of arrays of objects (operator [ ])
- passing objects as arguments by values, references or pointers
- returning objects from functions by value, reference or pointer
We will go into detail about everything class related in lessons to come.
Table of contents
- Operator Overloading
- Class Inheritance
- Exceptions
- Namespaces
- Templates
- Standard Library
- Additional Problems