C++, the definitive curly brace language. Or is it?
A basic class
In C++, classes have member functions, member variables, class functions and class variables. Accessibility can be one of public, protected or private, with public and private being the most common.
class Animal {
// Default access modifier at beginning of class is private
public: // Everybody can access this
// Constructors
Animal();
Animal(bool alive = true);
Animal(const Animal&); // Copy constructor
// Destructor
~Animal();
// Virtual function, can be overruled by a derived class
virtual string getDNA();
// A pure virtual function must be defined in a derived class.
// This class makes it an abstract class
virtual int getPopulation() = 0;
protected:
private:
};
A derived class
A derived class inherits from a base class. Functions from the base class can be explicitly called by using the class name as a specifier.
class Rabbit : Animal {
public:
// Member variables
int numberOfChildren;
// Member functions
Rabbit createOffspring();
// Constructor
Rabbit(string name) : Animal() {
numberOfRabbits++; // Not thread-safe but ok for this example
}
Rabbit(const Rabbit &originalRabbit); // Copy constructor
Rabbit~() {numberOfRabbits--; } // Destructor
virtual string description() = 0;
protected: // Accessible by derived classes
private: // Only accessible from class and friends
virtual string getName(); // Can be redefined in a derived class
string name;
virtual string getDNA() = 0;
static int numberOfRabbits; // Class variable
public:
virtual int getPopulation() {return Rabbit.getRabbitPopulation(); }
static int getRabbitPopulation() const { return numberOfRabbits; } // Class function
friend void print(Rabbit &);
};
// Definition of a class outside the class declaration
Rabbit::jump() {
}
Some other definitions
Implementation of the class functions and class variables can be defined outside of the class.
// Friend functions, not member of class
void print(Rabbit &rabbit) {
std::cout << rabbit.name;
}
int Rabbit::numberOfRabbits = 0; // Initialization outside of class