In C++, classes and objects are fundamental concepts of Object-Oriented Programming (OOP).
class
A class is a blueprint or template for creating objects. It defines properties (attributes) and behaviors (methods or functions) that the objects created from the class will have.
Properties (Attributes): Variables that hold the data or state of the object.
Methods (Functions): Functions that define the behavior of the object, i.e., what it can do.
Object
An object is an instance of a class. When you create an object from a class, you can access and modify its properties and call its methods.
Example of Class and Object:
#include <iostream>
#include <string> // For using the string type
using namespace std;
// Define a class called 'Employee'
class Employee {
public:
// Properties (Attributes)
string firstName;
string lastName;
int age;
// Method (Function)
void displayFullName() {
cout << "Full Name: " << firstName << " " << lastName << endl;
cout << "Emp's age " << age << endl;
}
};
int main() {
// Create an object of the class 'Employee'
Employee emp;
// Set properties (attributes)
emp.firstName = "John";
emp.lastName = "Taylor";
emp.age = 35;
// Call method (function)
emp.displayFullName();
return 0;
}
Output:
Emp's age 35
C++ Class and Object – Questions and Answers
Q 1: What is a class?
Ans: A blueprint for creating objects.
Q 2: What is an object?
Ans: An instance of a class.
Q 3: What can a class contain?
Ans: Data members and member functions.
Q 4: Why use classes?
Ans: To support Object-Oriented Programming.
Q 5: How do you create an object?
Ans: ClassName obj;
C++Class and Object – Objective Questions (MCQs)
Q1. What is a class in C++?
Q2. How do you create an object of a class Car?
Q3. Which of the following can a class contain?
Q4. What is the default access specifier for class members in C++?
Q5. Which of the following is the correct syntax for defining a class?