C++ Classes and Objects

What are Classes in C++?

A class is a user-defined data type or data structure that is declared with the keyword class, that has data members and member functions as its members. Its access is governed by the three access specifiers Public, Private or Protected. By default it is private.

Create a Class

class MyClass
{
public:
int number;
};

class MyClass– Here class is a keyword used to create a class called MyClass

public– The keyword public is an access specifier. It specifies that members of the class(MyClass) are also accessible from outside the class.

int number– This is the data member inside the class. int is the data type of the variable number

; -Semicolon marks the end of the class

What are Objects in C++?

An Object is an instance of a Class. When a class is defined, no memory is allocated but when an object is created, only then memory is allocated. 

ClassName ObjectName; // Syntax

What are Access Specifiers?

The public keyword in the above program is known as the access specifier. Access specifiers define how the members (attributes and methods) of a class can be accessed.

There are three types of access specifies in C++

public– The members of the public class are accessible from outside the class

class Public_Access // class class_name
{
 public:            // access specifier
 int a;             // Data-Member Declaration 
 void display();    // Member-Function declaration
}

private– The members of private class cannot be accessed from outside the class

class Private_Access //class class_name
{
 private:            // access specifier
 int a;              // Data-Member Declaration 
 void display();     // Member-Function declaration
}

protected–  The members of the protected class cannot be accessed from outside the class, however, they can be accessed in inherited classes.

class Protected_Access // class class_name
{
 protected:            // access specifier
 int a;                // Data-Member Declaration 
 void display();       // Member-Function Declaration
}
We will be happy to hear your thoughts

Leave a reply

Edusera
Logo
Open chat
1
Scan the code
Hello!👋
Can we help you?