0% found this document useful (0 votes)
19 views15 pages

C++ Features Vs C

The document outlines key features of C++ that are not present in C, including object-oriented programming concepts such as classes and objects, constructors and destructors, inheritance, polymorphism, templates, the Standard Template Library (STL), exception handling, RAII, and type casting. Each feature is explained with simple examples to illustrate their usage and benefits. These distinctions highlight C++'s capabilities for managing complex software systems compared to C.

Uploaded by

humayunahmedsust
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views15 pages

C++ Features Vs C

The document outlines key features of C++ that are not present in C, including object-oriented programming concepts such as classes and objects, constructors and destructors, inheritance, polymorphism, templates, the Standard Template Library (STL), exception handling, RAII, and type casting. Each feature is explained with simple examples to illustrate their usage and benefits. These distinctions highlight C++'s capabilities for managing complex software systems compared to C.

Uploaded by

humayunahmedsust
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

C++ Features vs C

please, give all these concepts of c++ which is not in C


details with code

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:

1. Classes and Objects (Object-Oriented Programming)


C++ allows the use of classes and objects to model real-world entities and behaviors. C
does not support classes and objects.

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;
}

2. Constructor and Destructor


C++ provides constructors and destructors to initialize and clean up objects, which is not
available in C.

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;
}

4. Polymorphism (Function Overloading and Virtual Functions)


C++ supports polymorphism. This can be achieved through function overloading or
overriding functions via virtual methods. C does not have function overloading or virtual
functions.

Function Overloading Example:

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;
}

Virtual Functions Example (Runtime Polymorphism):

cpp

#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class show function" << endl;
}
};

class Derived : public Base {


public:
void show() override {
cout << "Derived 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;
}

5. Templates (Generic Programming)


C++ introduces templates, allowing functions and classes to work with any data type.
This provides the power of generic programming, which C does not have.

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;
}

6. STL (Standard Template Library)


C++ provides the Standard Template Library (STL), which includes powerful data
structures like vectors, maps, and algorithms that are not present in C.

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;

void divide(int a, int b) {


if (b == 0) {

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;
}

8. RAII (Resource Acquisition Is Initialization)


C++ emphasizes RAII, where resources like memory or file handles are managed by
objects' constructors and destructors, which is not common in C. This ensures automatic
cleanup of resources when objects go out of scope.

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;
}

9. Type Casting (Static, Dynamic, Const, Reinterpret)


C++ provides various types of type casting such as static_cast , dynamic_cast ,
const_cast , and reinterpret_cast , which C does not support in this structured
manner.

cpp

#include <iostream>
using namespace std;

class Base {
public:
virtual void show() {
cout << "Base class show" << endl;
}
};

class Derived : public Base {


public:
void show() override {
cout << "Derived 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;
}

These features, such as Object-Oriented Programming (OOP), templates, exceptions, and


more, are key distinctions that make C++ a powerful language compared to C. Let me know if
you'd like to dive deeper into any of these topics!

Explain That I can learn easily

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++.

1. Classes and Objects (Object-Oriented Programming)


Classes: Think of a class like a blueprint for creating objects (real-world things). A class
defines what attributes (properties) and actions (methods) an object can have.

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;
}

2. Constructor and Destructor


Constructor: A special function that runs when you create an object. It’s used to set up
the initial state of the object.

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.

Example: A "Dog" class can inherit from an "Animal" class.

cpp

class Animal {
public:
void speak() {
cout << "Animal makes a sound!" << endl;
}
};

class Dog : public Animal {


public:
void speak() {
cout << "Dog barks!" << endl; // Overriding the parent method
}
};

int main() {
Dog myDog;
myDog.speak(); // Outputs: Dog barks!
return 0;
}

4. Polymorphism (Function Overloading and Virtual Functions)


Function Overloading: You can have multiple functions with the same name but
different parameters.

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;
}
};

class Dog : public Animal {


public:
void speak() override {
cout << "Dog barks!" << 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

template <typename T>


T add(T a, T b) {
return a + b;
}

int main() {
cout << add(5, 3) << endl; // int
cout << add(5.5, 3.3) << endl; // double
return 0;
}

6. STL (Standard Template Library)


STL is a collection of ready-made, generic classes and functions that can be used for
common tasks like managing data collections (vectors, lists, maps, etc.) and algorithms
(sorting, searching, etc.).

Example (Using a vector to store integers):

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.

Example: Trying to divide by zero will throw an exception.

cpp

void divide(int a, int b) {


if (b == 0) {
throw "Error: Division by zero!";
}
cout << a / b << endl;
}

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;
}

8. RAII (Resource Acquisition Is Initialization)


RAII is a technique where resources like memory or files are managed automatically by
objects. When an object is created, resources are acquired; when the object is destroyed,
resources are released.

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; }
};

class Dog : public Animal {


public:
void speak() override { cout << "Dog barks!" << 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

You might also like