CPP Example with Class
CPP Insruction and program for How to use Class
by Krishna
Posted on 27 Jun 2018 Category: c-plus-plus
Views: 1274
CPP Example with Class
One of the major features of C++ is ‘classes’. They provide a method for binding together data and functions which operate on them. Class is an extension of the idea of structure used in C and therefore classes are user defined data types.
Generally a class specification has two parts:
Class declarations
Class function definitions
The general form of a class declaration is
class class_name
{
private:
variable declarations;
function declarations;
public:
variable declarations;
function declarations;
};
The class body contains the declarations of variables and functions. These functions and variables are collectively called class members. The keywords private and public are known as visibility labels. The class members that are declared as private can be accessed only from within the class. While the public members can be accessed from outside the class. By default the members of a class are private.
Below program demonstrates the use of class
#include <iostream>
using namespace std;
class student
{
private:
char name[20];
int regno;
public:
void read();
void display();
};
void student::read()
{
cout<<"Enter Name:";
cin>>name;
cout<<"Enter RegisterNo.:";
cin>>regno;
}
void student::display()
{
cout<<"\tSTUDENT DETAILS\n";
cout<<"\nName:"<<name;
cout<<"\nRegisterNo.:"<<regno;
}
int main()
{
student s;
s.read();
s.display();
}
The program defines student as a new data of type class. In the main function s is the object of type student. These class objects are used to invoke the functions read() and display().
OUTPUT
Latest posts in c-plus-plus