Classes help you group related data and actions together. Objects are real examples made from classes.
Classes and objects in C++
Introduction
Syntax
C++
class ClassName { public: // data members (variables) // member functions (methods) }; // Create an object ClassName objectName;
Use public: to allow access to members from outside the class.
Objects are instances of classes and hold their own data.
Examples
Car with two pieces of data: brand and year. Then it creates an object myCar.C++
#include <string> using namespace std; class Car { public: string brand; int year; }; Car myCar;
Light has a function to turn it on. The object lamp uses that function.C++
class Light { public: bool isOn; void switchOn() { isOn = true; } }; Light lamp; lamp.switchOn();
Sample Program
This program creates a Dog class with a name and age. It has a function to bark. We make a dog named Buddy, tell it to bark, and print its age.
C++
#include <iostream> #include <string> using namespace std; class Dog { public: string name; int age; void bark() { cout << name << " says Woof!" << endl; } }; int main() { Dog myDog; myDog.name = "Buddy"; myDog.age = 3; myDog.bark(); cout << "Age: " << myDog.age << endl; return 0; }
Important Notes
Remember to use public: to make members accessible outside the class.
Each object has its own copy of the data members.
Functions inside classes are called methods and can use the object's data.
Summary
Classes group data and functions to model real things.
Objects are individual examples made from classes.
Use classes to organize and reuse your code better.
Practice
1. What is the main purpose of a
class in C++?easy
Solution
Step 1: Understand what a class represents
A class groups related data (variables) and functions (methods) to model real-world things.Step 2: Compare options with the definition
Only To group data and functions that represent a real-world concept correctly describes this purpose; others are unrelated to classes.Final Answer:
To group data and functions that represent a real-world concept -> Option AQuick Check:
Class = group data + functions [OK]
Hint: Classes bundle data and actions together [OK]
Common Mistakes:
- Thinking classes only store numbers
- Confusing classes with program speed
- Believing classes replace variables
2. Which of the following is the correct way to declare a class named
Car in C++?easy
Solution
Step 1: Recall C++ class declaration syntax
The correct syntax is:class ClassName { };with a semicolon at the end.Step 2: Check each option
class Car { }; matches the correct syntax. Options A, C, and D have syntax errors or wrong order.Final Answer:
class Car { }; -> Option AQuick Check:
class ClassName { }; syntax [OK]
Hint: Remember: class name follows 'class' keyword, ends with semicolon [OK]
Common Mistakes:
- Writing 'Car class' instead of 'class Car'
- Missing semicolon after class body
- Using parentheses after class name
3. What will be the output of this C++ code?
class Box {
public:
int length;
void setLength(int len) { length = len; }
int getLength() { return length; }
};
int main() {
Box box1;
box1.setLength(10);
std::cout << box1.getLength();
return 0;
}medium
Solution
Step 1: Understand the class methods
The methodsetLengthsets thelengthto 10 forbox1. The methodgetLengthreturns this value.Step 2: Trace the output statement
std::cout << box1.getLength();prints the value 10 stored inlength.Final Answer:
10 -> Option DQuick Check:
setLength(10) then getLength() = 10 [OK]
Hint: Setter sets value, getter returns it [OK]
Common Mistakes:
- Forgetting to call setLength before getLength
- Expecting default value 0 without initialization
- Confusing method names
4. Identify the error in this class definition:
class Person {
string name;
int age;
public:
void setName(string n) { name = n; }
void setAge(int a) { age = a; }
};medium
Solution
Step 1: Check class syntax
The class ends with a semicolon, and functions have correct return types (void). Data members are private by default, which is allowed.Step 2: Check for missing includes
The code usesstringbut does not include<string>header, which is required forstd::string.Final Answer:
Missing #include <string> header -> Option CQuick Check:
Use #include <string> for string type [OK]
Hint: Always include headers for standard types [OK]
Common Mistakes:
- Assuming private members need public keyword
- Forgetting to add semicolon after class
- Confusing function return types
5. Given this class:
What concept does this code demonstrate?
class Student {
int id;
string name;
public:
Student(int i, string n) : id(i), name(n) {}
void display() {
std::cout << "ID: " << id << ", Name: " << name << std::endl;
}
};
int main() {
Student s1(101, "Alice");
s1.display();
return 0;
}What concept does this code demonstrate?
hard
Solution
Step 1: Identify the special function in the class
The functionStudent(int i, string n) : id(i), name(n) {}is a constructor initializing the object's data members.Step 2: Check other options
There is no inheritance, no function overloading, and no static members shown.Final Answer:
Constructor initializing object data -> Option BQuick Check:
Constructor sets initial values [OK]
Hint: Look for function named as class for constructor [OK]
Common Mistakes:
- Confusing constructor with regular method
- Thinking this shows inheritance
- Assuming static members without keyword
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
