600 likes | 801 Views
C++ Classes. Definition, Constructors, Methods, Access Modifiers, Static/Instance members, . Learning & Development Team. http://academy.telerik.com. Telerik Software Academy. Table of Contents. Classes and Objects Concept Defining and Instantiating Classes
E N D
C++ Classes Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team http://academy.telerik.com Telerik Software Academy
Table of Contents • Classes and Objects Concept • Defining and Instantiating Classes • Constructors, Initialization & this keyword • Destructors • Methods • Operator Overloading • Static and Instance Members • Classes and const • Pointers to classes
Classes and Objects in Programming Modelling the Real World in Code
Classes and Objects Concept • Classes model real-world objects and define • Attributes (state, properties, fields) • Behavior (methods, operations) • Classes describe the structure of objects • Objects describe particular instance of a class • Properties hold information about the modeled object relevant to the problem • Operations implement object behavior
Classes and Objects in C++ • Classes in C++ can have members: • Fields, constants, methods, operators, constructors, destructors, … • Inner types (inner classes, structures) • Access modifiers define the scope of sets of members (scope) • public, private, protected • Members can be • static(class) or specific for a given object
Class Definition Example • Defining a simple class to represent a Jedi class Jedi { public: string name; intforceMastery; Jedi(string name, intforceMastery) { this->name = name; this->forceMastery = forceMastery; } string getName() { return this->name; } //example continues
Class Definition Example void Speak() { string sentence = "Greetings, I am "; switch(this->forceMastery) { case 0: sentence+="padawan"; break; case 1: sentence+="jedi-knight"; break; case 2: sentence+="master"; } sentence += " "; cout<<sentence + this->name<<endl; } };
Simple Class Definition Live Demo
Defining Classes in C++ Syntax, Keywords, Basic Members
Defining Classes in C++ • Classes are either defined with the class or struct keyword • Both syntaxes are almost the same • Class definition is in the form: class ClassName : InheritedClass1, InheritedClass2,... { access-modifier : //e.g. public: members//e.g.int a; orint answer(){return 42;} access-modifier : members ... }; Don't forget the semicolon after definition
Defining Classes in C++ • A class has a name • A class can "inherit" other classes • i.e. reuse their logic and members • A class declares accessibility of its members • Which members are visible from outside • Which members are visible from inheritors • Which members are only visible from inside • These are known as "access modifiers" or "scopes"
Defining Classes in C++ • Access modifiers in classes • public: accessible from anywhere outside or inside the class and its inheritors • protected: accessible from inside the class and from its inheritors • private: accessible only from inside the class • If not specified, members of a class are private • If not specified, members of a struct are public An access modifier affects all members, declared after it up to the next modifier (or up to the end of the class definition)
Defining Classes in C++ • Fields are the simplest members of classes • Fields are variables inside the class • Can be of any type, including other classes, or even of the same class • The latter case is usually called a recursive class • Can be initialized on declaration (C++11) • Keep in mind they can be changed by the constructor or other methods class Person { public: string name; int age = 0; };
Defining Classes in C++ • Creating objects of classes • Usually to use a class, you instantiate an object of that class • E.g. you instantiate a individual of type Person • Note: "instantiate", i.e. we create an instance. We haven't "initialized" it with values yet • Accessing object members • Members are accessed through the "." operator Person somebody; somebody.name = "Waspy"; cout<<somebody.name;
Creating Classes & Instantiating Objects Live Demo
Constructors Initializing Objects, Calling Constructors
Constructors • Objects need to be initialized before usage • If not, we could get undetermined results • Just like with uninitialized variables • Objects usually can't be initialized by literal: • E.g. can't initializea Person with just a name, or just a number, it needs both to set its age and name • Some classes need even more values • Some classes need complex initialization logic Person somebody = "Tony"; Person somebody = 5; //both of the above are wrong
Constructors • Constructors are special functions, responsible for initializing objects • Declared inside the class • Have same name as the class • Accept parameters like normal functions • Can be overloaded like normal functions • Have direct access to the class members • Don't have a return type • Execute after inline initialization • i.e. if a field has a value at declaration, the constructor can change it
Constructors • Constructor for the Person class class Person { public: string name; int age = 0; Person(string nameParameter, intageParameter) { name = nameParameter; age = ageParameter; //changes the 0 value of age } };
Constructors • Constructors can be called in several ways • Parenthesis after identifier, at declaration • Class name, followed by parenthesis • i.e. create a temporary & assign it to an instance • Same as 2), but with "new" • Allocates dynamic memory for objects • Returns a pointer to the memory Person p("Tony", 22); Person p = Person("Tony", 22); Person *p = new Person("Tony", 22);
Basic Constructors Live Demo
Constructors • Mistaken constructor (ambiguous identifiers) • name and age here hide the class fields • Function variables and parameters are "more local" than global or class variables class Person { public: string name; int age = 0; Person(string name, intage) { name = name; age = age; } }; These assignments do nothing – they set the parameters to their own values
Constructors & this • The this keyword • Explicitly refers to the current class instance • Used to explicitly point to a instance member • Even if it is hidden by local variables class Person { public: string name; int age = 0; Person(string name, intage) { this->name = name; this->age = age; } };
Constructors & this • More info on the this keyword • Typed pointer to current instance • E.g. for a Person instance named p, this could be expressed as: Person* this = &p; • Can be used in any constructor • or function (method) inside the class • Recommended way of accessing instance members don't try to compile that
Using "this" in Constructors Live Demo
Overloading Constructors • Constructors can be overloaded class Person { public: string name; int age = 0; Person(string name, int age) { this->name = name; this->age = age; } Person(string personInfo) //e.g. format: "022Tony"-> Tony, age 22 { this->age = 100*(personInfo[0] - '0') + 10*(personInfo[1] - '0') + personInfo[2] - '0'; this->name = personInfo.substr(3); } };
Overloading Constructors • Constructor parameters can have default values, just like functions class Person { public: string name; intage; Person(string name = "Anonymous", intage = 0) { this->name = name; this->age = age; } };
Constructor Overloading Live Demo
Destructors • Destructors are special functions, called when an object is freed from memory • A destructor is usually responsible for: • Cleaning up allocated dynamic memory by the instance • Resetting any changes a constructor could have made outside the instance • Syntax: same as constructor, with a ~ prefix and no parameters ~Person(){ ... }
Destructors Live Demo
Methods Functions in Classes
Methods • Methods are functions, belonging to a class • Methods have all the properties of functions • Can accept parameters and be overloaded • Can have default values for parameters • Have return values • Methods have access to other class members • Recommended to use the this pointer • Methods can be accessed through any instance through the "." operator
Methods class Person { public: string name; int age = 0; Person(string name, int age) { this->name = name; this->age = age; } string GetInfo() { stringstreaminfoStream; infoStream<<this->name<<", age: "<<this->age<<endl; return infoStream.str(); } };
Methods Live Demo
Operator Overloading Redefining basic operations for complex classes
Operator Overloading • Classes define new types in C++ • Types interact with assignments, function calls and operators • Instances of a new class can also use operators • By defining how operators work on its instances • This is called operator overloading • Syntax type operator sign (parameters) { /*... body ...*/ }
Operator Overloading • Example overloading + for 2D vectors class Vector2D { public: double x; double y; Vector2D(double x = 0, double y = 0) { this->x = x; this->y = y; } Vector2D operator + (const Vector2D &other) { return Vector2D(this->x + other.x, this->y + other.y); } };
Basic Operator Overloading Live Demo
Operator Overloading • Overloaded operators are just special functions • Using operators is just calling those functions • Operators can be overloaded both as members and as non-members • Members can access the calling object through the this pointer • Non-members take an additional parameter to refer to the object, calling the operator
Operator Overloading • Form of common overloaded operators:
Operator Overloading • Calling operators can be done in two ways • As normal operators in expressions • By their function name i.e.: • prefixed with operator keyword, • followed by the actual operator • and its parameters in parantheses c = a + b; c = a.operator+ (b);
Static Members Members Common for all Instances
Static Members • There is data (and behavior) which can be the same for all instances of a class • E.g. average person age – doesn't need to be specific for each instance • Static members • Single common variables for objects of a class • Marked by the static keyword • Must be initialized from outside the class • To avoid reinitialization
Static Members • Example: Person static members (1) class Person { private: static intpersonCount; static inttotalPersonAge; public: string name; int age; Person(string name = "", int age = 0) { this->name = name; this->age = age; Person::totalPersonAge += this->age; Person::personCount++; } //example continues
Static Members • Example: Person static members (2) • Two ways of accessing static members: • Through class name, followed by :: • Through instance, like any other member ~Person() { Person::totalPersonAge -= this->age; Person::personCount--; } static intgetAveragePersonAge() { return Person::totalPersonAge / Person::personCount; } };
Static Members Live Demo
Classes and const Restricting Modifications Compile-Time
Classes and const • Class members can be defined const • Fields follow the same rules as const variables • Methods and operators cannot modify the instance they are called on • Syntax: place const after method parentheses class Person { ... string getInfo() const { stringstreaminfoStream; infoStream<<this->name<<", age: "<<this->age<<endl; return infoStream.str(); } }
Classes and const • const methods are frequently used • Mark a non-modifying method • Hence, required by many standard library methods, accepting references • A const reference to an object can only call const methods • An object can be const like any variable • Only consturctor & const methods can be called const Person p = Person("Tony", 20); cout<<p.getPersonInfo()<<endl;