CPP Program to Implement Classes with Primitive Data Members

Aim:

To write a program in C++ to prepare a student Record using class and object.

  • Simple Classes for understanding objects, member functions and Constructors
  • Classes with primitive data members

Defining Class and Creating Objects:

  • When we define any class, we are not defining any data, we just define a structure or a blueprint, as to what the object of that class type will contain and what operations can be performed on that object.

Below is the syntax of the class definition,

class ClassName
{
    Access specifier: 
    Data members;
    Member Functions()
    {
        // member function defintion
    }
};
Code language: JavaScript (javascript)

Here is an example, we have made a simple class named Student with appropriate members,

class Student
{
    public:
    int rollno;
    string name;
};
Code language: PHP (php)

So it’s clear from the syntax and example, class definition starts with the keyword “class” followed by the class name. Then inside the curly braces comes the class body, For example:

class Student
{
    public:
    int rollno;
    string name;
} A,B;
Code language: PHP (php)

Here A and B are the objects of class Student, declared with the class definition. We can also declare objects separately like we declare variables of primitive data types. In this case, the data type is the class name, and the variable is the object.

int main()
{
    // creating object of class Student
    Student A;
    Student B;
}
Code language: JavaScript (javascript)

Both A and B will have their own copies of data members i.e. roll no and name and we can store different values for them in these objects.

Algorithm:

  1. Create a class record.
  2. Read the name, Regno, mark1, mark2, mark3 of the student.
  3. Calculate the average of the mark as Avg=mark1+mark2+mark3/3
  4. Display the student record.
  5. Stop the program.

Program:

#include<iostream>
using namespace std;
class record
{
private:
char name[100];
int regno;
int mark[3];
float avg;
public:
void getdata()
{
cout<<"ENTER STUDENT NAME :"<<endl;
cin>>name;
cout<<"ENTER REG NO :"<<endl;
cin>>regno;
cout<<"ENTER THE 3 MARKS"<<endl;
for(int i=0;i<3;i++)
cin>>mark[i];
avg=(mark[0]+mark[1]+mark[2])/3;
}
void SHOWdata()
{
cout<<"\nNAME  :"<<name<<endl;
cout<<"REG NO  :"<<regno<<endl;
cout<<"AVERAGE :"<<avg<<endl;
}
};

Execution:

INPUT : 
ENTER STUDENT NAME :
XYZ
ENTER REG NO :
1234
ENTER THE 3 MARKS :
99 98 97

OUTPUT : 
NAME: XYZ
REG NO: 1234
AVERAGE: 98

Result:

Thus, the Implementation Classes with Primitive Data Members was executed successfully.

Leave a Comment