C++ Classes
Post on 25-Feb-2016
35 Views
Preview:
DESCRIPTION
Transcript
C++ ClassesDefinition, Constructors, Methods, Access
Modifiers, Static/Instance members,
Learning & Development Teamhttp://academy.telerik.com
Telerik Software Academy
Table of Contents1. Classes and Objects Concept2. Defining and Instantiating Classes3. Constructors, Initialization & this
keyword Destructors
4. Methods5. Operator Overloading6. Static and Instance Members7. Classes and const8. Pointers to classes
2
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 Jediclass Jedi{public: string name; int forceMastery;
Jedi(string name, int forceMastery) { 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 DefinitionLive 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; or int 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
ConstructorsInitializing 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 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 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, int ageParameter) { name = nameParameter; age = ageParameter; //changes the 0 value of age }};
Constructors Constructors can be called in several waysa) 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);
Basic ConstructorsLive 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, int age) { 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, int age) { 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 ConstructorsLive Demo
Overloading Constructors
Constructors can be overloadedclass 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 functionsclass Person {public: string name; int age; Person(string name = "Anonymous", int age = 0) { this->name = name; this->age = age; }};
Constructor OverloadingLive 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(){ ... }
DestructorsLive Demo
MethodsFunctions 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
Methodsclass Person{public: string name; int age = 0;
Person(string name, int age) { this->name = name; this->age = age; }
string GetInfo() { stringstream infoStream; infoStream<<this->name<<", age: "<<this->age<<endl; return infoStream.str(); }};
MethodsLive Demo
Operator OverloadingRedefining 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
Syntaxtype operator sign (parameters) { /*... body ...*/ }
Operator Overloading Example overloading + for 2D vectorsclass 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 OverloadingLive 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:Expression Operator Member 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) a TYPE A::operator TYPE() -
Overloading Operators as
Members an Non-MembersLive Demo
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 paranthesesc = a + b;
c = a.operator+ (b);
Static MembersMembers 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 int personCount; static int totalPersonAge;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 int getAveragePersonAge() { return Person::totalPersonAge / Person::personCount; }};
Static MembersLive Demo
Classes and constRestricting 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 { stringstream infoStream; 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;
Classes and constLive Demo
Pointers to ClassesInstances in Dynamic Memory
Pointers to Classes 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;
Pointers to ClassesLive 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, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране
Николай Костов - блог за програмиранеC# курс, програмиране, безплатно
?? ? ?
??? ?
?
? ?
??
?
?
? ?
Questions?
?
C++ Classes
http://algoacademy.telerik.com
Exercises1. 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
Exercises (2)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 4S.
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
Exercises (3)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<Call>.
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
Exercises (4)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
top related