Download presentation
Presentation is loading. Please wait.
Published byColleen Myrtle Atkins Modified over 8 years ago
1
Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team http://academy.telerik.com Telerik Software Academy
2
1. Classes and Objects Concept 2. Defining and Instantiating Classes 3. Constructors, Initialization & this keyword Destructors 4. Methods 5. Operator Overloading 6. Static and Instance Members 7. Classes and const 8. Pointers to classes 2
3
Modelling the Real World in Code
4
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 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
Defining a simple class to represent a Jedi class Jedi {public: string name; string name; int forceMastery; int forceMastery; Jedi(string name, int forceMastery) Jedi(string name, int forceMastery) { this->name = name; this->name = name; this->forceMastery = forceMastery; this->forceMastery = forceMastery; } string getName() string getName() { return this->name; return this->name; } //example continues } //example continues
7
void Speak() void Speak() { string sentence = "Greetings, I am "; string sentence = "Greetings, I am "; switch(this->forceMastery) switch(this->forceMastery) { case 0: case 0: sentence+="padawan"; sentence+="padawan"; break; break; case 1: case 1: sentence+="jedi-knight"; sentence+="jedi-knight"; break; break; case 2: case 2: sentence+="master"; sentence+="master"; } sentence += " "; sentence += " "; cout name name<<endl; }};
8
Live Demo
9
Syntax, Keywords, Basic Members
10
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; or int answer(){return 42;} members //e.g. int a; or int answer(){return 42;} access-modifier : members members...}; Don't forget the semicolon after definition
11
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
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
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; string name; int age = 0;};
14
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
Live Demo
16
Initializing Objects, Calling Constructors
17
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 initialize a 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 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
Constructor for the Person class class Person {public: string name; string name; int age = 0; int age = 0; Person(string nameParameter, int ageParameter) Person(string nameParameter, int ageParameter) { name = nameParameter; name = nameParameter; age = ageParameter; //changes the 0 value of age age = ageParameter; //changes the 0 value of age }};
20
Constructors can be called in several ways a)Parenthesis after identifier, at declaration b)Class name, followed by parenthesis i.e. create a temporary & assign it to an instance c)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
Live Demo
22
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; string name; int age = 0; int age = 0; Person(string name, int age) Person(string name, int age) { name = name; name = name; age = age; age = age; }}; These assignments do nothing – they set the parameters to their own values
23
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; string name; int age = 0; int age = 0; Person(string name, int age) Person(string name, int age) { this->name = name; this->name = name; this->age = age; this->age = age; }};
24
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
Live Demo
26
Constructors can be overloaded class Person { public: string name; string name; int age = 0; int age = 0; Person(string name, int age) Person(string name, int age) { this->name = name; this->name = name; this->age = age; this->age = age; } Person(string personInfo) //e.g. format: "022Tony"-> Tony, age 22 Person(string personInfo) //e.g. format: "022Tony"-> Tony, age 22 { this->age = 100*(personInfo[0] - '0') + this->age = 100*(personInfo[0] - '0') + 10*(personInfo[1] - '0') + 10*(personInfo[1] - '0') + personInfo[2] - '0'; personInfo[2] - '0'; this->name = personInfo.substr(3); this->name = personInfo.substr(3); }};
27
Constructor parameters can have default values, just like functions class Person {public: string name; string name; int age; int age; Person(string name = "Anonymous", int age = 0) Person(string name = "Anonymous", int age = 0) { this->name = name; this->name = name; this->age = age; this->age = age; }};
28
Live Demo
29
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
Live Demo
31
Functions in Classes
32
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
class Person {public: string name; string name; int age = 0; int age = 0; Person(string name, int age) Person(string name, int age) { this->name = name; this->name = name; this->age = age; this->age = age; } string GetInfo() string GetInfo() { stringstream infoStream; stringstream infoStream; infoStream name age name age<<endl; return infoStream.str(); return infoStream.str(); }};
34
Live Demo
35
Redefining basic operations for complex classes
36
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...*/ } type operator sign (parameters) { /*... body...*/ }
37
Example overloading + for 2D vectors class Vector2D {public: double x; double x; double y; double y; Vector2D(double x = 0, double y = 0) Vector2D(double x = 0, double y = 0) { this->x = x; this->x = x; this->y = y; this->y = y; } Vector2D operator + (const Vector2D &other) Vector2D operator + (const Vector2D &other) { return Vector2D(this->x + other.x, return Vector2D(this->x + other.x, this->y + other.y); this->y + other.y); }};
38
Live Demo
39
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
Form of common overloaded operators: ExpressionOperatorMember function Non-member function @a + - * & ! ~ ++ -- A::operator@()operator@(A) a@++ --A::operator@(int)operator@(A,int) a@b + - * / % ^ & | == != = > && ||, A::operator@(B)operator@(A,B) a@b = += -= *= /= %= ^= &= |= >= [] A::operator@(B)- a(b,c...)() A::operator()(B,C...) - a->b->A::operator->()- (TYPE) aTYPEA::operator TYPE()-
41
Live Demo
42
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.+ (b); c = a.operator+ (b);
43
Members Common for all Instances
44
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
Example: Person static members (1) class Person {private: static int personCount; static int personCount; static int totalPersonAge; static int totalPersonAge;public: string name; string name; int age; int age; Person(string name = "", int age = 0) Person(string name = "", int age = 0) { this->name = name; this->name = name; this->age = age; this->age = age; Person::totalPersonAge += this->age; Person::totalPersonAge += this->age; Person::personCount++; Person::personCount++; } //example continues //example continues
46
Example: Person static members (2) Two ways of accessing static members: Through class name, followed by :: Through instance, like any other member ~Person() ~Person() { Person::totalPersonAge -= this->age; Person::totalPersonAge -= this->age; Person::personCount--; Person::personCount--; } static int getAveragePersonAge() static int getAveragePersonAge() { return Person::totalPersonAge / Person::personCount; return Person::totalPersonAge / Person::personCount; }};
47
Live Demo
48
Restricting Modifications Compile-Time
49
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 string getInfo() const { stringstream infoStream; stringstream infoStream; infoStream name age name age<<endl; return infoStream.str(); return infoStream.str(); }}
50
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;
51
Live Demo
52
Instances in Dynamic Memory
53
As mentioned, creating an instance with the new keyword returns a pointer A pointer can also be obtained by using the reference operator & All typical pointer operations are valid Access to members is done through the -> operator Person *samPtr = new Person("Sam", 18); Person frodo = Person("Frodo", 18); Person *frodoPtr = &frodo; cout<<samPtr->getPersonInfo()<<endl;
54
Live Demo
55
форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране http://algoacademy.telerik.com
56
1. Define a class that holds information about a mobile phone device: model, manufacturer, price, owner, battery characteristics (model, hours idle and hours talk) and display characteristics (size and number of colors). Define 3 separate classes (class GSM holding instances of the classes Battery and Display ). 2. Define several constructors for the defined classes that take different sets of arguments (the full information for the class or part of it). Assume that model and manufacturer are mandatory (the others are optional). All unknown data fill with null. 3. Add an enumeration BatteryType (Li-Ion, NiMH, NiCd, …) and use it as a new field for the batteries. 56
57
4. Add a method in the GSM class for displaying all information about it. 5. Use methods to encapsulate the data fields inside the GSM, Battery and Display classes. Ensure all fields hold correct data at any given time. 6. Add a static field IPhone4S in the GSM class to hold the information about iPhone 4 S. 7. Write a class GSMTest to test the GSM class: Create an array of few instances of the GSM class. Display the information about the GSMs in the array. Display the information about the static field IPhone4S. 57
58
8. Create a class Call to hold a call performed through a GSM. It should contain date, time, dialed phone number and duration (in seconds). 9. Add a property CallHistory in the GSM class to hold a list of the performed calls. Try to use the class vector. 10. Add methods in the GSM class for adding and deleting calls from the calls history. Add a method to clear the call history. 11. Add a method that calculates the total price of the calls in the call history. Assume the price per minute is fixed and is provided as a parameter. 58
59
12. Write a class GSMCallHistoryTest to test the call history functionality of the GSM class. Create an instance of the GSM class. Add a few calls. Display the information about the calls. Assuming that the price per minute is 0.37 calculate and print the total price of the calls in the history. Remove the longest call from the history and calculate the total price again. Finally clear the call history and print it. 59
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.