260 likes | 549 Views
Writing a Good Program 5. Objects and Classes in C++. Computer Programming and Basic Software Engineering. 5. Objects and Classes in C++. 5.1 Basic Object Oriented Programming. Computer Programming and Basic Software Engineering. 5. Objects and Classes in C++. What is an Object?.
E N D
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ 5.1 Basic Object Oriented Programming
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ What is an Object? • The real world is composed of different kinds of objects:buildings, men, women, dogs, cars, etc. • Each object has its own states and behaviors. Behaviors Color = Red Brand = Ferrari Speed = 200 mph Gear = 4 States Changing Gear Steering Braking Accelerating Variables and functions
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ What is a Software Object? • Software designers use the same idea to ease programmers to develop their software • Software is also composed of different kind of software objects • Each software object also has its own states and behaviors. Variables (States) Color = Grey Size = 2cm x 2cm Shape = Rectangular Button Method (Behavior) Press( ) (protruded)
Computer Programming and Basic Software Engineering Encapsulation 5. Objects and Classes in C++ • Hiding information within an object’s nucleus • Provide a public interface for interacting with it • Advantages to software developers • Modularity:An object can be easily passed around in the system (Otherwise, you need to think about how many files you need to bundle together to pass to your friends) • Information hiding: Users need not go into details of the object before using the object (E.g., you don’t need to know the circuit of a TV set if you want to watch TV) • Safety:Users of the object may not directly access the internal state of the object. This reduces the possibility of erroneous situations. Library Reusability
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ What is a Class? • A Class is a blueprint or prototype that defines the variables and methods common to all objects of a certain kind • Every object of a Class is an instance of that class • Benefit - Reusability • This arrangement saves effort in developing a number of objects of the same kind. Usually objects of a class are used many times in an application Objects of class button
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ The Button Class: Variables Color (e.g. Grey) Size (e.g. 2cm x 2cm) Shape (e.g. Rectangular) (protruded) Method Press( ) Instantiation Instance of Button Class Instantiation Instance of Button Class
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ 5.2 Objects and Classes in C++
Computer Programming and Basic Software Engineering Declaring Classes in C++ 5. Objects and Classes in C++ • To declare a class, use the class keyword as follows • Declaring this class does NOT allocate memory for a Cat. • Only tell the compiler what a Cat is, how big a Cat is (by member variables, e.g.itsAge, itsWeight), what a Cat would do (by member functions, e.g.Meow()). • Declaration of classes should be placed in the header file and included into your program. • class Cat • { • unsigned int itsAge; // Member variable • unsigned int itsWeight;// Member variable • void Meow(); // Member function • }; P.12 Definition of Meow() should follow somewhere #include
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Declaring an Object of a Class • When a class is defined, we can further define the objects of that class: • Cat Frisky; // define one of the Cats call Frisky • It states that we are going to handle a Cat called Frisky. • It is similar to declaring a number of the type integer • int xyz; // define one of the integers call xyz • Obviously, if one declares two cats as follows • Cat Frisky, Felix; // define two Cats • Frisky is never equal to Felix, although they both belong to the class Cat, i.e. they are cats.
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Accessing Class Members Variable and methods • When an object is defined, we can access the members of that object based on its class definition. • For example, if we want to know the weight of Frisky: • unsigned int weight = Frisky.itsWeight; • // Get the weight of Frisky • The operator ‘.’ allows us to access the members of the object. • Similarly, if we want to know the age of Frisky: • unsigned int age = Frisky.itsAge; • // Get the age of Frisky • If we want to ask Frisky to meow: • Frisky.Meow(); // Ask Frisky to execute meow()
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Accessing Class Members • Never access directly to class • Cat.itsAge = 5; // Don’t do that! Cat is class • It is because Cat is only a template of all cats. A different cat may have a different age. • If we want to assign the age of Frisky, we write: • Frisky.itsAge = 5; // Set the age of Frisky to 5 • Also, if the class doesn’t define a member, you cannot use it. • Frisky.bark(); // Frisky has no bark() defined • Frisky.itsColor = 5;// Also error, because the class • // Cat does not have itsColor P.9
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Private Versus Public • Members can be divided into public members or private members. • Private members of a class are those members that can only be accessed by methods of that class. • By default, all members are private. • Public members of a class are those members that can be accessed by other class objects and functions. • This mechanism provides the privacy or security to the information of a class that requires protection. Typically, access private members by public methods.
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Private Versus Public #include <iostream> // for cout using namespace std; class Cat // declare the class { int itsAge; int itsWeight; }; int main() { Cat Frisky; Frisky.itsAge = 5; // assign to the member variable cout << "Frisky is a cat who is "; cout << Frisky.itsAge << " years old.\n"; return 0; } An error is generated since by defaultitsWeight and itsAgeare private. They cannot be accessed even by main().
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Private Versus Public #include <iostream> // for cout using namespace std; class Cat // declare the class { public: int itsAge; int itsWeight; }; int main() { Cat Frisky; Frisky.itsAge = 5; // assign to the member variable cout << "Frisky is a cat who is "; cout << Frisky.itsAge << " years old.\n"; return 0; } Now itsWeight and itsAgeare public members. They can be accessed by main().
Computer Programming and Basic Software Engineering How Private Variables Are Used? 5. Objects and Classes in C++ P.18 P.21 #include <iostream> // for cout using namespace std; class Cat // declare the class Cat { public: void SetAge (int age); int GetAge(); void SetWeight (int weight); int GetWeight(); private: int itsAge; int itsWeight; }; int Cat::GetAge() { return itsAge; } void Cat::SetAge(int age) { itsAge = age; } Public Accessor Methods Read/write Private member variables Accessor methods provide access to private members since they are in the same class.
Computer Programming and Basic Software Engineering Implementing Class Methods 5. Objects and Classes in C++ • Member functions declared in a class are only prototypes of these functions. • Actual implementation (the operations performed by the function) should be separately described. #include <iostream> // for cout using namespace std; class Cat // declare the class Cat { public: int GetAge(); private: int itsAge; }; int Cat::GetAge() { return itsAge; } To indicate GetAge() is a function of class Cat. Publicly known Only the developer knows That’s the implementation
Computer Programming and Basic Software Engineering Exercise 5.2a 5. Objects and Classes in C++ P.16 Based on the program in page 16, write a program that will first print the age and weight of a cat called Felix, and then it asks the user to input the age and weight of that cat. To do that, you need to do the following things: a. Complete the implementation of the member functions GetWeight() and SetWeight(). b. Add the main() function that prints the current status of a cat Felix and ask for user’s input to modify the status. c. Build the result program and note the result. d. Before you ask the user to input the age and weight, what are their initial values? Are they the ones you expect? Age and weight Use run-time debugger
Computer Programming and Basic Software Engineering Constructors and Destructors 5. Objects and Classes in C++ • How do we initialize an object? • By means of the constructor of the class • Every class should have a constructor. • User can define its own constructor for the class. • Otherwise, the compiler will make one for the user although it does nothing. • Constructor is a function of which the compiler will call if an object of this class is constructed (created). • Besides constructor, every class has also a destructor that will be called when the object of that class is destructed (removed). In memory
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ A typical Class definition with user- definedconstructor and destructor • class Cat • { • public: • Cat(int initialAge);// Constructor of Cat • ~Cat();// Destructor of Cat • int GetAge(); • void SetAge(int Age); • void Meow(); //public function • private: • int itsAge; • }; • Cat::Cat (int initialAge) • { itsAge = initialAge; • } • Cat::~Cat() • { • } • void Cat::Meow() {} Implementation of constructor When any object of the class Cat is constructed, this function is called and in effect it will set itsAge to the parameter passed. Implementation of destructor When any object of the class Cat is destructed, this function is called which in effect does nothing.
Computer Programming and Basic Software Engineering Constructors and Destructors 5. Objects and Classes in C++ • A possible main() function for the class Cat above is as follows: A Cat Frisky is constructed here The constructor is called and the parameter 5 is passed to the constructor and in turn initializes the private member variable itsAge to 5. // some lines of p.20 // some lines of p.16 int main() { Cat Frisky(5); Frisky.Meow(); cout << "Frisky is a cat who is "; cout << Frisky.GetAge() << " years old.\n"; Frisky.Meow(); //Meow() does nothing here Frisky.SetAge(7); cout << "Now Frisky is "; cout << Frisky.GetAge() << " years old.\n"; Frisky.Meow(); return 0; }
Computer Programming and Basic Software Engineering const Member Functions 5. Objects and Classes in C++ • It is possible that some functions will never change the value of any member. • It is desirable to declare them as const member function. • Then, the compiler will automatically check if there is any inconsistency in the program. • It helps to debug the program. • In the example above, obviously GetAge() and GetWeight()will not change any member • Hence they can be declared as const as follows: • int GetAge() const; // add the keyword const when • int GetWeight() const; // you declare the functions Read only
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Exercise 5.2b From the program you wrote in exercise 5.2a, a. Add the constructor and destructor such that the initial age and weight of Felix is 5 and 10 respectively. b. Use the const keyword to define the class methods that will not modify the member variables.
Computer Programming and Basic Software Engineering Exercise 5.2c 5. Objects and Classes in C++ Identify the errors in the following program. The program is divided into 3 parts: class declaration, member functions implementation and the main(). Fix the errors and verify your results by building the program. #include <iostream> // for cout using namespace std; class Cat // begin declaration of the class { public: // begin public section Cat(int initialAge); // constructor ~Cat(); // destructor int GetAge() const; // accessor function void SetAge(int Age); // accessor function void Meow(); // general function private: int itsAge; // member variable };
Computer Programming and Basic Software Engineering 5. Objects and Classes in C++ Cat::Cat(int initialAge) { itsAge = initialAge; cout << "Cat Constructor\n"; } Cat::~Cat() { cout << "Cat Destructor\n"; } int Cat::GetAge() { return (itsAge++); } void Cat::SetAge(int age) { itsAge = age; } void Cat::Meow() { cout << "Meow.\n"; } int main() { Cat Frisky; Frisky.Meow(); Frisky.Bark(); Frisky.itsAge = 7; return 0; }
Acknowledgment • The slides are based on the set developed by Dr. Frank Leung (EIE).