Skip to main content

Programming in C++: Tokens, Identifiers, Variables and Constants; Data types, Operators, Control statements, Functions Parameter Passing, Virtual Functions, Class and Objects; Constructors and Destructors; Overloading, Inheritance, Templates, Exception and Event Handling; Streams and Files; Multifile Programs.

 Let's cover each topic related to programming in C++ in detail:

1. Tokens, Identifiers, Variables, and Constants:
These concepts in C++ are similar to those in C. Tokens are the smallest individual units, identifiers are used to name variables, functions, etc., variables store data, and constants are fixed values.

Example:
```cpp
#include <iostream>

int main() {
    int num = 42;  // 'int', 'main', 'return', '42', '=', ';' are tokens
    std::cout << "Value of num: " << num << std::endl;
    const float PI = 3.14;  // 'const', 'float', 'PI', '=', '3.14', ';' are tokens
    return 0;
}
```

2. Data Types:
C++ supports various data types such as int, float, char, bool, etc., and allows the creation of user-defined data types using classes.

Example:
```cpp
#include <iostream>

int main() {
    int age = 30;  // 'int' is a data type
    float pi = 3.14;  // 'float' is a data type
    char letter = 'A';  // 'char' is a data type
    bool isTrue = true;  // 'bool' is a data type

    return 0;
}
```

3. Operators:
C++ provides various operators such as arithmetic, relational, logical, etc., to perform operations on variables and constants.

Example:
```cpp
#include <iostream>

int main() {
    int a = 5, b = 3;
    int sum = a + b;  // '+' is an operator
    bool isEqual = (a == b);  // '==' is a relational operator

    if (a > b) {  // '>' is a relational operator
        std::cout << "a is greater than b" << std::endl;
    }

    return 0;
}
```

4. Control Statements:
C++ supports control statements like if-else, switch-case, while, for, etc., to control the flow of the program.

Example (if-else statement):
```cpp
#include <iostream>

int main() {
    int num = 5;

    if (num > 0) {
        std::cout << "Positive number" << std::endl;
    } else {
        std::cout << "Non-positive number" << std::endl;
    }

    return 0;
}
```

5. Functions Parameter Passing:
C++ allows passing parameters to functions by value, reference, or pointer.

Example (pass by value):
```cpp
#include <iostream>

void increment(int x) {
    x++;
}

int main() {
    int num = 5;
    increment(num);
    std::cout << "Value of num: " << num << std::endl;  // Output: 5

    return 0;
}
```

6. Virtual Functions:
Virtual functions enable dynamic polymorphism in C++ using inheritance and virtual keyword.

Example:
```cpp
#include <iostream>

class Animal {
public:
    virtual void sound() {
        std::cout << "Animal makes a sound." << std::endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        std::cout << "Dog barks." << std::endl;
    }
};

class Cat : public Animal {
public:
    void sound() override {
        std::cout << "Cat meows." << std::endl;
    }
};

int main() {
    Animal* animal1 = new Dog();
    Animal* animal2 = new Cat();

    animal1->sound();  // Output: Dog barks.
    animal2->sound();  // Output: Cat meows.

    delete animal1;
    delete animal2;

    return 0;
}
```

7. Class and Objects:
Classes are user-defined data types that contain data members and member functions. Objects are instances of classes.

Example:
```cpp
#include <iostream>

class Person {
public:
    std::string name;
    int age;

    void introduce() {
        std::cout << "Hi, I am " << name << " and I am " << age << " years old." << std::endl;
    }
};

int main() {
    Person person1;  // Object of class Person
    person1.name = "John";
    person1.age = 30;
    person1.introduce();  // Output: Hi, I am John and I am 30 years old.

    return 0;
}
```

8. Constructors and Destructors:
Constructors are special member functions that are automatically called when an object is created. Destructors are called when an object goes out of scope or is explicitly deleted.

Example:
```cpp
#include <iostream>

class MyClass {
public:
    MyClass() {
        std::cout << "Constructor called." << std::endl;
    }

    ~MyClass() {
        std::cout << "Destructor called." << std::endl;
    }
};

int main() {
    MyClass obj;  // Output: Constructor called.

    return 0;  // Output: Destructor called.
}
```

9. Overloading:
C++ allows defining multiple functions with the same name but different parameter types (or number of parameters). This is called function overloading.

Example:
```cpp
#include <iostream>

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

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

int main() {
    std::cout << add(5, 3) << std::endl;  // Output: 8
    std::cout << add(3.14f, 2.71f) << std::endl;  // Output: 5.85

    return 0;
}
```

10. Inheritance:
Inheritance allows a class to inherit the properties and behaviors of another class, promoting code reuse.

Example:
```cpp
#include <iostream>

class Vehicle {
public:
    void start() {
        std::cout << "Vehicle started." << std::endl;
    }
};

class Car : public Vehicle {
public:
    void drive() {
        std::cout << "Car is being driven." << std::endl;
    }
};

int main() {
    Car car;
    car.start();  // Output: Vehicle started.
    car.drive();  // Output: Car is being driven.

    return 0;
}
```

11. Templates:
Templates allow writing generic functions and classes that can work with different data types.

Example (Function Template):
```cpp
#include <iostream>

template<typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    std::cout << add(5, 3) << std::endl;  // Output: 8
    std::cout << add(3.14f, 2.71f) << std::endl;  // Output: 5.85

    return 0;
}
```

12. Exception and Event Handling:
C++ provides try-catch blocks for handling exceptions that may occur during program execution.

Example:
```cpp
#include <iostream>

int main() {
    try {
        int result = 10 / 0;  // Division by zero


    } catch (const std::exception& e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }

    return 0;
}
```

13. Streams and Files:
C++ supports streams for input and output operations. Files can be read from and written to using file streams.

Example (File Handling - Writing to a File):
```cpp
#include <iostream>
#include <fstream>

int main() {
    std::ofstream file("example.txt");
    if (file.is_open()) {
        file << "This is an example.";
        file.close();
    } else {
        std::cout << "Unable to open the file." << std::endl;
    }

    return 0;
}
```

14. Multifile Programs:
C++ programs can be split into multiple files using header files and implementation files.

Example:
```cpp
// main.cpp
#include <iostream>
#include "myclass.h"

int main() {
    MyClass obj;
    obj.sayHello();

    return 0;
}
```

```cpp
// myclass.h
#ifndef MYCLASS_H
#define MYCLASS_H

class MyClass {
public:
    void sayHello();
};

#endif
```

```cpp
// myclass.cpp
#include "myclass.h"
#include <iostream>

void MyClass::sayHello() {
    std::cout << "Hello, World!" << std::endl;
}
```

These are the fundamental concepts of programming in C++. Understanding these concepts will enable you to write efficient and maintainable C++ code.

Comments

Popular posts from this blog

Web Programming: HTML, DHTML, XML, Scripting, Java, Servlets, Applets

 Web programming encompasses various technologies and concepts used to develop web applications. Let's explore each of them in detail: 1. HTML (Hypertext Markup Language): HTML is the standard markup language used to create the structure and content of web pages. It uses tags to define elements like headings, paragraphs, images, links, forms, etc. Example: ```html <!DOCTYPE html> <html> <head>     <title>My Web Page</title> </head> <body>     <h1>Hello, World!</h1>     <p>This is a paragraph.</p>     <img src="image.jpg" alt="Image">     <a href="https://www.example.com">Visit Example</a> </body> </html> ``` 2. DHTML (Dynamic HTML): DHTML is a combination of HTML, CSS, and JavaScript that allows web pages to become more dynamic and interactive. Example (DHTML with JavaScript): ```html <!DOCTYPE html> <htm...

Tokens, Identifiers, Data Types, Sequence Control, Subprogram Control, Arrays, Structures, Union, String, Pointers, Functions, File Handling, Command Line Argumaents, Preprocessors in C with example

 Let's discuss each concept briefly and provide examples for better understanding: 1. Tokens: Tokens are the smallest building blocks in C programming. They include keywords, identifiers, constants, strings, operators, and punctuators. Example: ```c #include <stdio.h> int main() {     int num = 42;  // 'int', 'main', 'return', '42', '=', ';' are tokens     printf("Hello, World!");  // 'printf', '(', ')', 'Hello, World!', ';', are tokens     return 0;  // 'return', '0', ';' are tokens } ``` 2. Identifiers: Identifiers are names used to identify variables, functions, or other user-defined entities. Example: ```c int age = 30;  // 'age' is an identifier (variable name) void displayMessage() {  // 'displayMessage' is an identifier (function name)     // function body } ``` 3. Data Types: Data types define the type of data that can be stored in ...

Place holder and control character in c language

 In the C programming language, placeholders and control characters are used to format and control the output of text in console-based programs. They are special characters or sequences of characters that have specific meanings. Here are the placeholders and control characters commonly used in C: 1. Placeholders:    - %d: Used to display signed integers.      Example: printf("The value is %d", 10);    - %u: Used to display unsigned integers.      Example: printf("The value is %u", 10);    - %f: Used to display floating-point numbers.      Example: printf("The value is %f", 3.14);    - %c: Used to display characters.      Example: printf("The character is %c", 'A');    - %s: Used to display strings (sequence of characters).      Example: printf("The string is %s", "Hello");    - %p: Used to display memory addresses (pointers)...