C++ Features Vs C
C++ Features Vs C
Certainly! C++ introduces several key concepts and features that are not present in C. These
features enhance the power and flexibility of C++, making it more suited for large, complex
software systems. Here are some of the notable concepts, along with example code:
cpp
#include <iostream>
using namespace std;
class Dog {
public:
string name;
int age;
void bark() {
cout << name << " is barking!" << endl;
}
};
int main() {
Dog myDog;
myDog.name = "Buddy";
myDog.age = 3;
myDog.bark(); // Call the bark method
return 0;
}
1/15
cpp
#include <iostream>
using namespace std;
class Car {
public:
string model;
Car(string m) { // Constructor
model = m;
cout << "Car created: " << model << endl;
}
~Car() { // Destructor
cout << "Car destroyed: " << model << endl;
}
};
int main() {
Car myCar("Toyota");
// Destructor will be called when the object goes out of scope
return 0;
}
3. Inheritance
C++ supports inheritance, allowing one class to inherit properties and behaviors from
another. This is a fundamental feature of object-oriented programming, which is absent
in C.
cpp
#include <iostream>
using namespace std;
class Animal {
public:
void speak() {
cout << "Animal makes a sound." << endl;
}
};
2/15
class Dog : public Animal {
public:
void speak() {
cout << "Dog barks!" << endl;
}
};
int main() {
Dog myDog;
myDog.speak(); // Calls the Dog's speak method
return 0;
}
cpp
#include <iostream>
using namespace std;
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};
int main() {
Calculator calc;
cout << "Int sum: " << calc.add(10, 20) << endl;
cout << "Double sum: " << calc.add(10.5, 20.5) << endl;
3/15
return 0;
}
cpp
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};
int main() {
Base *basePtr;
Derived derivedObj;
basePtr = &derivedObj;
basePtr->show(); // Calls Derived's show() method due to virtual function
return 0;
}
cpp
#include <iostream>
using namespace std;
4/15
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << "Int sum: " << add(10, 20) << endl;
cout << "Double sum: " << add(10.5, 20.5) << endl;
return 0;
}
cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> vec = {1, 2, 3, 4, 5};
for (int i : vec) {
cout << i << " ";
}
return 0;
}
7. Exception Handling
C++ supports exception handling using try , catch , and throw . C does not have built-
in support for exceptions.
cpp
#include <iostream>
using namespace std;
5/15
throw "Division by zero error!";
}
cout << "Result: " << a / b << endl;
}
int main() {
try {
divide(10, 0);
} catch (const char* e) {
cout << "Exception: " << e << endl;
}
return 0;
}
cpp
#include <iostream>
#include <fstream>
using namespace std;
class FileHandler {
private:
ifstream file;
public:
FileHandler(const string &filename) {
file.open(filename);
if (!file) {
throw "Failed to open file!";
}
cout << "File opened successfully." << endl;
}
~FileHandler() {
if (file.is_open()) {
file.close();
cout << "File closed automatically." << endl;
6/15
}
}
};
int main() {
try {
FileHandler fh("example.txt");
} catch (const char* e) {
cout << "Exception: " << e << endl;
}
return 0;
}
cpp
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class show" << endl;
}
};
int main() {
Base *basePtr = new Derived();
Derived *derivedPtr = dynamic_cast<Derived*>(basePtr); // Safe downcast
if (derivedPtr) {
7/15
derivedPtr->show(); // Calls Derived's show()
}
delete basePtr;
return 0;
}
Absolutely! Let me break these concepts down in a simple way to help you understand them
easily. I'll also provide straightforward examples so that you can see how each feature works
in C++.
Objects: Objects are instances of a class. They are actual things created from the class.
Example: Imagine a "Car" class. Every car object has a model and a color, and can perform
an action, like driving.
cpp
class Car {
public:
string model;
string color;
void drive() {
cout << "The " << color << " " << model << " is driving!" << endl;
}
};
int main() {
8/15
Car myCar;
myCar.model = "Tesla";
myCar.color = "red";
myCar.drive(); // The red Tesla is driving!
return 0;
}
Destructor: A special function that runs when an object is destroyed. It’s used to clean
up any resources (like memory) used by the object.
Example: A car object can print a message when it's created or destroyed.
cpp
class Car {
public:
Car() { // Constructor
cout << "A new car is created!" << endl;
}
~Car() { // Destructor
cout << "The car is destroyed!" << endl;
}
};
int main() {
Car myCar; // When this object is created, the constructor runs
return 0; // When it goes out of scope, the destructor runs
}
3. Inheritance
9/15
Inheritance allows a new class (child class) to reuse the code of an existing class (parent
class). The child class inherits the attributes and behaviors of the parent class.
cpp
class Animal {
public:
void speak() {
cout << "Animal makes a sound!" << endl;
}
};
int main() {
Dog myDog;
myDog.speak(); // Outputs: Dog barks!
return 0;
}
Virtual Functions: Functions in a base class that can be overridden by derived classes.
This allows for different behavior based on the object type.
Example (Function Overloading): You can overload the add function to handle different
types of data.
cpp
10/15
class Calculator {
public:
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; }
};
int main() {
Calculator calc;
cout << calc.add(10, 20) << endl; // Calls the int version
cout << calc.add(10.5, 20.5) << endl; // Calls the double version
return 0;
}
Example (Virtual Functions): When you call a method through a pointer to the base class,
C++ decides at runtime which method to call based on the actual object type.
cpp
class Animal {
public:
virtual void speak() {
cout << "Animal makes a sound!" << endl;
}
};
int main() {
Animal* animal = new Dog(); // Points to a Dog object, but is an Animal pointer
animal->speak(); // Outputs: Dog barks!
delete animal;
return 0;
}
11/15
5. Templates (Generic Programming)
Templates allow you to write functions and classes that work with any data type. You
don’t need to write separate functions for each data type.
Example: A simple function that adds two numbers of any type (e.g., int , double ).
cpp
int main() {
cout << add(5, 3) << endl; // int
cout << add(5.5, 3.3) << endl; // double
return 0;
}
cpp
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
cout << num << " "; // Outputs: 1 2 3 4 5
}
12/15
return 0;
}
7. Exception Handling
Exception Handling allows your program to handle errors gracefully without crashing.
You use try , catch , and throw to handle and throw errors.
cpp
int main() {
try {
divide(10, 0); // This will throw an error
} catch (const char* msg) {
cout << msg << endl; // Output: Error: Division by zero!
}
return 0;
}
13/15
Example: If you open a file, the file is closed automatically when the object goes out of
scope.
cpp
class FileHandler {
public:
FileHandler(const string& filename) {
file.open(filename);
if (!file) {
throw "File not found!";
}
}
~FileHandler() {
if (file.is_open()) {
file.close();
cout << "File closed automatically!" << endl;
}
}
private:
ifstream file;
};
int main() {
try {
FileHandler handler("example.txt");
} catch (const char* msg) {
cout << msg << endl;
}
return 0;
}
9. Type Casting
Type Casting allows you to convert one type of variable into another. C++ provides
several types of casting for different scenarios ( static_cast , dynamic_cast ,
const_cast , reinterpret_cast ).
14/15
Example: A safe cast between pointers of related classes.
cpp
class Animal {
public:
virtual void speak() { cout << "Animal sound" << endl; }
};
int main() {
Animal* animal = new Dog();
Dog* dog = dynamic_cast<Dog*>(animal); // Safe cast to Dog
if (dog) {
dog->speak(); // Dog barks!
}
delete animal;
return 0;
}
I hope this breakdown makes it clearer! If any part is still confusing, feel free to ask, and I can
explain further. 😊
15/15