Toggle Menu

C++


C++ has classes which allows it to be an object-oriented language, although it is not a "pure OOP language" because it tempers its OOP features for efficiency and practicality.

Object-Oriented Programming

Object-oriented programming (OOP) is a popular and powerful programming technique. The main characteristics of OOP are:
  1. Encapsulation
    • Form of information hiding or abstraction by restricting access to only accessors and mutators
    • Abstraction decomposes complex systems into smaller components
    • Data Validation: ensure only appropriate data is assigned to class private member variables
  2. Inheritance
    • Objects can relate to each other with a "has a" (has a class inside its definition) or "is a" (derived class) relationship
  3. Polymorphism
    • Multiple methods with the same name but different functionality
    • Overriding (run-time polymorphism) and overloading (compile-time polymorphism)

Sample C++ Program

#include <iostream>
using namespace std;

int main() {
  int num;
  cout << "Enter a number:" << endl;
  cin >> num;
  cout << "Your number is: " << num << endl;
  return 0;
}
  1. #include <iostream> using namespace std; - allows us to use console input and output
  2. int main() - every C++ program is essentially a function definition for a function called main. The main function is executed when the function is run and the statements within the braces are executed.
  3. cout << - outputs text to stdout.
  4. cin >> - reads from stdin.
  5. return 0; - ends the program successfully.
  6. Note that each statement ends with a semicolon ;