Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team Telerik Software Academy.

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

HTML Forms, GET, POST Methods Tran Anh Tuan Edit from Telerik Academy
Make swiftly iOS development Telerik Academy Telerik Academy Plus.
Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Coding JavaScript the expressive way Learning & Development Telerik Software Academy.
Asynchronous Programming with C# and WinRT
Unleash the Power of JavaScript Tooling Telerik Software Academy End-to-end JavaScript Applications.
Touch and Gestures with Xamarin Forms
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Hybrid or Native?! Doncho Minkov Telerik Software Academy Senior Technical Trainer
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
With Mocha and Karma Telerik Academy Telerik Software Academy.
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Telerik Software Academy ASP.NET Web Forms.
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Telerik Software Academy End-to-end JavaScript Applications.
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
Closures, Function Scope, Nested Functions Learning & Development Team Telerik Software Academy.
Language enhancements and additions Learning & Development Team Telerik Software Academy.
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Using the Standard.NET Framework Classes Telerik Software Academy C# Fundamentals – Part 2.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Telerik Software Academy Databases.
Integer, Floating-Point, Text Data, Variables, Literals Telerik Corporation
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
Creating and Initializing Arrays, Accessing Elements, Multiple Dimensions Learning & Development Team Telerik Software Academy.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Classes, Fields, Constructors, Methods, Properties Telerik Software Academy Object-Oriented Programming.
Presentation transcript:

Definition, Constructors, Methods, Access Modifiers, Static/Instance members, Learning & Development Team Telerik Software Academy

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

Modelling the Real World in Code

 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 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

 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

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

Live Demo

Syntax, Keywords, Basic Members

 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

 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"

 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)

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

 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;

Live Demo

Initializing Objects, Calling 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 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

 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

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

 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);

Live Demo

 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

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

 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

Live Demo

 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); }};

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

Live Demo

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

Live Demo

Functions in Classes

 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

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

Live Demo

Redefining basic operations for complex classes

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

 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); }};

Live Demo

 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

 Form of common overloaded operators: ExpressionOperatorMember function Non-member + - * & ! ~ * / % ^ & | == != = > && ||, = += -= *= /= %= ^= &= |= >= [] a(b,c...)() A::operator()(B,C...) - a->b->A::operator->()- (TYPE) aTYPEA::operator TYPE()-

Live Demo

 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);

Members Common for all Instances

 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

 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

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

Live Demo

Restricting Modifications Compile-Time

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

 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;

Live Demo

Instances in Dynamic Memory

 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;

Live Demo

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен 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# Николай Костов - блог за програмиране

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

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

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

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