1 / 59

C++ Classes

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

kevyn
Download Presentation

C++ Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. C++ Classes Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team http://academy.telerik.com Telerik Software Academy

  2. 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

  3. Classes and Objects in Programming Modelling the Real World in Code

  4. 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

  5. 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

  6. 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

  7. 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; } };

  8. Simple Class Definition Live Demo

  9. Defining Classes in C++ Syntax, Keywords, Basic Members

  10. 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

  11. 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"

  12. 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)

  13. 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; };

  14. 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;

  15. Creating Classes & Instantiating Objects Live Demo

  16. Constructors Initializing Objects, Calling Constructors

  17. 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

  18. 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

  19. 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 } };

  20. 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);

  21. Basic Constructors Live Demo

  22. 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

  23. 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; } };

  24. 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

  25. Using "this" in Constructors Live Demo

  26. 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); } };

  27. 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; } };

  28. Constructor Overloading Live Demo

  29. 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(){ ... }

  30. Destructors Live Demo

  31. Methods Functions in Classes

  32. 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

  33. 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(); } };

  34. Methods Live Demo

  35. Operator Overloading Redefining basic operations for complex classes

  36. 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 ...*/ }

  37. 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); } };

  38. Basic Operator Overloading Live Demo

  39. 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

  40. Operator Overloading • Form of common overloaded operators:

  41. Overloading Operators as Members an Non-Members Live Demo

  42. 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);

  43. Static Members Members Common for all Instances

  44. 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

  45. 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

  46. 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; } };

  47. Static Members Live Demo

  48. Classes and const Restricting Modifications Compile-Time

  49. 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(); } }

  50. 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;

More Related