Class
In OOP, a class is an extensible program-code-template (blueprint) for creating objects, providing initial values for state and implementations of behavior.
Different Types of Classes:
- Base / Parent / Super Class Ex: Animal
- Class from which many child classes can be created.
- Derived / Child / Sub class Dog
- The subclasses inherit the characteristics of a superclass.
- Abstract Base Class
- Concrete Class
A class is composed of:
- Fields / member variables
- Methods
Danger
Public fields variables in classes are BAD. We don’t want to allow anyone to modify the variables of a class. So always put it inside
privatewhen you can.Else, you don’t really need a class, just use
structs so anyone can access them. Because the fields in structs are modifying by anyone.
Some of the challenges we are facing in OOP is dealing with sharing objects. Ex: Child and balloon classes Imagine Balloons being passed around, create them as pointers.
How would this work in code?
Class vs. Struct
structdefault access specifier is publicclassdefault access specifier is private- Use
structwhen all you want is structured data, and - Use
classes when you want methods, Inheritance, or generics
When to use
structvsclass?Classes are nicer: > 1. construction / destruction is guaranteed (on the Stack) > 2. can enforce legal value ranges via access specifiers (public / private / protected) … although you can do these with
structas wellBut if you don’t need this, use
struct.
Properties
- Classes can extend other classes, i.e. Inheritance
- Can treat instances of related classes in a uniform manner, i.e. Polymorphism
C++
Ballon b1;
//Ballon b2(); -> BAD because it confuses it as a function
Ballon b3{};see about Constructor and Initializer because I am still confused by these things.
dog = Dog()Other Important Concepts
- Public / Protected / Private: See Method Safety Levels
- static variables and methods
- Constructor
- Copy constructor
- Destructor
- const keyword
- Declaration vs. Definition
bool isEmpty() const; // This makes sure nothing in the class is modified