Classes in C++


What is a class?

A class in C++ is a user-defined data type that consists of data member and member functions. A class leads the programming towards object-oriented programming. Data members are the variables that store the data, and member functions are the user-defined functions that manipulate the variables. Class is declared using the “class” keyword.

Syntax :

class class_name{ Access specifier : Data members/variables; Member functions {} };

A class in C++ is a user-defined data type that consists of data member and member functions. A class leads the programming towards object-oriented programming. Data members are the variables that store the data, and member functions are the user-defined functions that manipulate the variables. Class is declared using the “class” keyword.

  • Public: public refers to that everyone can access class data without any limit.
  • Protected: protected means that not everyone can access the data of the class, only the classes inherited from that class or the child classes of that class can access the data.
  • Private: private means no one can access the data present in the private section. Only the methods currently in that class can access the data.

Example:

#include <iostream> using namespace std; class knowledge2life { // Access specifier public: // Member Data string str; // Member Functions() void display() { cout << "welcome to " << str; } }; int main() { // Declare an object of class knowledge2life knowledge2life obj1; // accessing data member obj1.str = "knowledge2life.com"; // accessing member function obj1.display(); return 0; }

OUTPUT:

string type

Here you can see the variable a is in the public section, so it can be public and the display() method is in the public area so that everyone can access it.