• June 12, 2021

PHSARIT

Bring Technology Ideas with you

 Class and Objects in C++ programming

What is a Class in OOP programming language?

Class just like the other OOP which is refering to the collection of objects. By general definition, Class is a blueprint of objects and it is defined by a users (programmers). Each of the class must be contained with access specifiers that the key elements for other main program to access their objects within the class. Those access specifiers have:

  1. Public is allowing the other outside program can access to their objects without any set or get method.
  2. Private is allowing the other outside to access their objects unless the program using get or set method

What is an Object in the Class?

Objects are the member variables or function members in the Class. Objects can be defined by the chracteristics which are call datatypes. Every Class must consists of objects to work on various types within the class prototype.

How to define Class in C++ programming?

To define Class in C++ programming, you need to start with the class keyword and follow by your defining name within the open and close of {} and the simicolon ; as below:

class Students
{
  //Variabe with datatype
  // void grade()
      {
      }
};

How to access Class and its data objects in main() Function?

To access the Class in the main() function you need to declare the Class Name which you have created within new name in the main() function as the following

Students myStudent;
// to access their objects
myStudent.variable name;

See the full example!

Let’s create a class called Students and call this class to use in main function. See the code below:

#include<iostream>
#include<string>
#include<queue>
using namespace std;

// define class
class user_info { // keyword class YourClassname{};
  //some data/objects must be having datatype
public: //everyone can access these objects now
  string userpass;
  int userid;
  string username;
  string role;
  double salary;

  
};

int main()

{
  user_info userlogin1; // call classname New Name of the class;
  userlogin1.userid = 12;
  userlogin1.username = "Tola";
  userlogin1.userpass = "he@mtola";
  userlogin1.role = "Adminstrator";
  userlogin1.salary = 250.90;
  cout << "User information: " << endl;
  cout << "User ID is: " << userlogin1.userid << endl;
  cout << "Username is: " << userlogin1.username << endl;
  cout << "Password is: " << userlogin1.userpass << endl;
  cout << "Role is: " << userlogin1.role << endl;

  system("pause == 0");
}

We have used the public key as we want the program in main to access their objects.

Result:

    Sample of Class in C++ programming

    Related post