Introduction
The biggest difference between C++ and C is object-oriented programming. Although I understand some concepts about object-oriented programming and have written some functions, I rarely use them in practice. This article is a quick summary of Chapter 15 of C++ Primer.
Overview
Object-oriented programming, also known as OOP, has three core ideas: data abstraction, inheritance, and dynamic binding. Data abstraction refers to the separation of declaration and implementation, inheritance refers to the subclass obtaining all members of the parent class, and dynamic binding means calling different functions based on the class type when invoking class functions.
Declaring Base Classes and Derived Classes
The following code provides a simple example, declaring a base class animal and a derived class cat.
#include <stdio.h>
#include <iostream>
class animal
{
public:
virtual void eat(){};
};
class cat : public animal
{
public:
void eat() { std::cout << "eat fish" << std::endl; }
};
int main()
{
cat c;
c.eat();
}
Type Conversion and Inheritance
Pointers and references of derived classes can be converted to pointers or references of base classes, but pointers or references of base classes cannot be converted to those of derived classes. This means that an object pointed to by a base class pointer could be a base class or a derived class, but definitely not a parent class of the base class.
A derived class object can be assigned to a base class, but only the base class portion will be copied.
Virtual Functions
Virtual functions are resolved at runtime. Continuing with our example above, suppose we write a new function called doeat that internally calls the eat method of animal. For animal, eat is “eat meat or grass”, but the final displayed result is “eat fish”. This proves that at runtime, when the doeat function calls animal’s eat method, the eat method finds the real object cat’s eat method and calls it.
class animal
{
public:
virtual void eat() { std::cout << "eat meat or grass" << std::endl; };
};
class cat : public animal
{
public:
void eat() { std::cout << "eat fish" << std::endl; }
};
void doeat(animal &a) { a.eat(); }
int main()
{
cat c;
doeat(c);
}
Additionally, to develop good habits, it’s best to use the override keyword in derived classes to explicitly declare overridden virtual functions.
Pure Virtual Functions
Assigning a value of 0 after defining a virtual function declares a pure virtual function. Pure virtual functions are equivalent to interfaces, and derived classes must implement these interfaces.
Abstract Base Classes
Classes containing pure virtual functions are abstract base classes. Abstract base classes cannot be instantiated.
Example: Text Line Query Program
Given a text, we need to query its contents. Supporting word queries and logical queries.