Implement a C++ Program to Define a Class and Create Objects
One of the key features that makes C++ a powerful language is its support for Object-Oriented Programming (OOP). OOP allows programmers to model real-world entities using classes and objects, making code modular, reusable, and easier to maintain.
🔹 What is a Class?
A class in C++ is a user-defined blueprint or prototype from which objects are created. It contains data members (variables) and member functions (methods) that operate on the data.
Syntax:
class ClassName {
// Data members
// Member functions
};
🔹 What is an Object?
An object is an instance of a class. When a class is defined, no memory is allocated until an object of that class is created.
✅ C++ Program: Define a Class and Create Objects
Let’s create a simple program that defines a class named `Student` and uses it to create and display student details.
#include <iostream>
using namespace std;
// Define the class
class Student {
private:
int rollNo;
string name;
public:
// Method to input student data
void inputDetails() {
cout << "Enter Roll Number: ";
cin >> rollNo;
cout << "Enter Name: ";
cin.ignore(); // To clear newline character from buffer
getline(cin, name);
}
// Method to display student data
void displayDetails() {
cout << "\nStudent Details:\n";
cout << "Roll Number: " << rollNo << endl;
cout << "Name: " << name << endl;
}
};
// Main function
int main() {
// Create object of Student class
Student s1;
// Call class methods using object
s1.inputDetails();
s1.displayDetails();
return 0;
}
🔍 Output Example
Enter Roll Number: 101
Enter Name: Vivek Bhardwaj
Student Details:
Roll Number: 101
Name: Vivek Bhardwaj
🧠 Explanation
Class Definition:
The `Student` class has two private data members: `rollNo` and `name`, and two public member functions: `inputDetails()` and `displayDetails()`.
Object Creation:
Inside the `main()` function, we create an object `s1` of type `Student`.
Method Invocation:
Using `s1`, we call `inputDetails()` to input the values and `displayDetails()` to print them.
`cin.ignore()` Usage:
We use `cin.ignore()` to handle newline issues when mixing `cin` and `getline()`.
Comments
Post a Comment