C++ Basics
-
C++ is one of the world's most popular programming language. It was developed by Bjarne Stroustrup, as an extension to the C language which provides object-oriented features and security to the data which was absent in C language. It is portable also and can be used to develop applications that can be adapted to multiple platforms.
-
Variables in C++ are used to store values in memory, while data types define the kind and size of data a variable can hold. Common data types include int, float, double, and String, among others.
int age = 30; float marks = 45.90; double price = 19.99; String name = "Amit Aryan";
-
Operators are symbols that perform operations on variables and values.
Operators in C++ can be classified into 6 types:
1. Arithematic Operators
2. Assignment Operators
3.Relational Operators
4. Logical Operators
5. Bitwise Operators
6. Other Operators
These are essential for manipulating data and making decisions in your programs.int a = 10 + 20; int b = 5 - 1; int result = 6 * 2;
-
Control structures like if-else, switch, and loops (for, while, do-while) help in controlling the flow of your C++ programs, allowing you to make decisions and repeat actions as needed.
if (condition) { // Code to execute when the condition is true } else { // Code to execute when the condition is false }
-
Functions (methods) are reusable blocks of code that perform specific tasks. They improve code organization and make it easier to maintain and understand.
void myFunction(){ // code to be executed }
-
Arrays are used to store multiple values of the same type in C++. They are fundamental for working with collections of data.
int[] numbers = {1, 2, 3, 4, 5};
-
Object-Oriented Programming (OOP) is a paradigm in C++ that focuses on creating objects and classes. This concept helps in organizing and modeling real-world entities.
class MyClass { public: int myNum; string myString; };
-
Inheritance allows one class (subclass or derived class) to inherit attributes and methods from another class (superclass or base class). It facilitates code reuse and extensibility.
class Vehicle { // Base class public: string brand = "Ford"; void honk() { cout << "Tuut, tuut! \n" ; } }; class Car: public Vehicle { // Derived class public: string model = "Mustang"; }; int main() { Car myCar; myCar.honk(); cout << myCar.brand + " " + myCar.model; return 0; }
-
Polymorphism enables objects of different classes to be treated as objects of a common superclass. This promotes flexibility and dynamic method invocation in C++ programs.
class Animal { // Base class public: void animalSound() { cout << "The animal makes a sound \n"; } }; class Pig : public Animal { // Derived class public: void animalSound() { cout << "The pig says: wee wee \n"; } }; class Dog : public Animal { // Derived class public: void animalSound() { cout << "The dog says: bow wow \n"; } };