Classes and Objects in C++

C++ProgrammingServer Side Programming

Classes are the prime features of C++ as they support OOPS concepts and are user defined data types. Classes provide the specification for an object and contain data variables as well as functions to manipulate the data in a single package.

Class Definitions

A class definition starts with the keyword class and then the class name. After that the class body is defined. It is enclosed by curly braces. A class definition should either contain a semicolon or a list of definitions after it.

An example of a class definition in C++ is as follows.

class student {
   int rollno;
   char name[50];
   float marks;
};

The above class contains the details of a student, namely its roll number, name and marks.

Object Definitions

When a class is defined, it is only a specification. There is no memory or storage allocated at that time. So the object is created from the class to access the data and functions defined in the class. A class can also be called the blueprint for an object.

The declaration of an object of class student is given as follows.

Student stu1;

A program that demonstrates classes and objects in C++ is given as follows.

Example

 Live Demo

#include <iostream>
using namespace std;
class Student {
   public:
   int rollno;
   char name[50];
   float marks;
   void display() {
      cout<<"Roll Number: "<< rollno <<endl;
      cout<<"Name: "<< name <<endl;
      cout<<"Marks: "<< marks <<endl;
   }
};
int main() {
   Student stu1 = {1, "Harry", 91.5};
   stu1.display();
   return 0;
}

Output

Roll Number: 1
Name: Harry
Marks: 91.5

In the above program, first the class student is defined. It contains the details about the student such as roll number, name and marks. It also contains a member function display() that displays all the student details. The code snippet that demonstrates this is as follows.

class student {
   public:
   int rollno;
   char name[50];
   float marks;
   void display() {
      cout<<"Roll Number: "<< rollno <<endl;
      cout<<"Name: "<< name <<endl;
      cout<<"Marks: "<< marks <<endl;
   }
};

In the function main(), the object of the class student is defined with the student details. Then these details are displayed with a function call to display(). This can be seen as follows.

student stu1 = {1, "Harry", 91.5};
stu1.display();
raja
Published on 09-Oct-2018 06:12:17
Advertisements