Classes

Class is a template / blueprint which stores the properties/attributes and behaviors of objects. Class is a user-defined data type.

Objects

Object is an entity which has its properties and behavior. For example, car is an object. It has properties like its color, weight, number etc. and behavior like it can accelerate, it can stop etc.

  • Properties of objects: Data members declared inside the class.
  • Behavior of objects: Members functions declared inside the class.

So, properties and behaviors are members of class and declared inside the class.

Now we will practically implement the concept of classes and objects.

Class

Class can have data members or members functions. They can be public, private or protected which we will discuss later. Keep in mind that public members can be accessed everywhere.

Exploring a simple basic example

Member Functions

Members functions are defined inside the class and they show the behavior of objects. They are also called methods. If I say, "My brother can say hello". This is the behavior of my brother.

Now we will make objects which can do addition, subtraction, multiplication and division.

Scope Resolution Operator

If we want to keep the code inside the class clean, we can declare functions inside class and define them outside the class using scope resolution operator(::).

  1. Local Variables: Local Variables are declared and initialized inside the methods, constructors or blocks. They will be destroyed when method has completed.
  2. Instance Variables: Instance variables are defined within a class but outside methods. They are initialized when the class is instantiated.
  3. Class Variables: These are declared within a class outside methods with static keyword.

Practice Exercises

Complete these exercises to reinforce your learning and earn XP

Sign in to track your progress and earn XP!
Exercise 1 of 2Easy

What is a blueprint for creating objects called?

10 XP~2 min
Exercise 2 of 2Easy

A function defined inside a class is called a ___.

10 XP~2 min