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
private
when you can.Else, you don’t really need a class, just use
struct
s 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
struct
default access specifier is publicclass
default access specifier is private- Use
struct
when all you want is structured data, and - Use
class
es when you want methods, Inheritance, or generics
When to use
struct
vsclass
?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
struct
as 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++
see about Constructor and Initializer because I am still confused by these things.
Other Important Concepts
- Public / Protected / Private: See Method Safety Levels
- static variables and methods
- Constructor
- Copy constructor
- Destructor
- const keyword
- Declaration vs. Definition