1 / 17

Structures Revisited

An exploration of structures and classes in C++, from aggregates to member functions, highlighting the differences and benefits of each.

munsond
Download Presentation

Structures Revisited

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. Structures Revisited • what is an aggregate construct? What aggregate constructs have we studied? • what is a structure? what is the keyword to define a structure? • what are structures used for? • why is a structure definition a type? What is built-in type? • is a structure definition an executable statement? Can it be put in a header file? • why includeing a header file with a structure definition multiple times is a problem? how is this problem solved? • what are #define #ifndef #endif? • what is a structure variable? • what is the term for elements of a structure? • do elements of the same structure (different structures) have to have unique names? • how can structures be initialized? what happens when one structure variable is assigned the value of another? • can structure variables be directly compared? passed as parameters? by value? by reference? can a function return a structure? • can one structure be included in another structure? What is a substructure? • can a structure include an array? how can an array of structures be declared?

  2. Classes aggregating code and data

  3. What’s Wrong with Structures? • modular program – can be logically partitioned into parts for understanding and maintenance • consider implementing date: • as structure: struct Date{ int month; int day; int year; }; • and a set of functions manipulating dates: void setDate(Date &d, int m, int d, int y); void addYear(Date &d, int n); bool compare(Date &d1, Date &d2); • problems: • there is no explicit connection between data type (structure) and these functions • it does not specify that the functions listed should be the only ones that access and modify date variables • if there is a bug in Date manipulation - it can be anywhere in the program • if modification of Date is needed - all program needs to be updated • the program is usually not modular

  4. Class Definition • class is an aggregate construct combining related code and data • class may contain member variables (attributes) and member functions (methods) • member variables and member function prototypes are declared within class definition • member functions can manipulate member variables without accepting them as parameters class Date { // class name public: // ignore this for now void set(int, int, int); intgetDay(); int month_; int day_; int year_; }; // don’t forget the semicolon • style: member variable name has trailing underscore to distinguish from scalar variable • a variable of type class is called object (how is a variable of type structure called?) Date mybday; • the object is said to belong to the class or be an instance of the class • each object has member variables and can call member functions of its class • state of the object – values of all member variables • accessing members is done using dot-operator: mybday.set(10, 26, 99); cout << mybday.day_;

  5. Public and Private Members • public: private:access modifiers – control the way the class members are accessed (why do we want to do that?) • public member can be accessed within member functions (no scope resolution needed) and outside (with dot operator) • private member - can only be accessed within member functions • example class Date { // class name public: void set(int, int, int); int getDay(); private: int month_; int day_; int year_; }; // don’t forget semicolon • make member variables private, make functions either public or private. This restricts manipulation of variables to member function which makes debugging and changes in class easier • examples: mybday.set(10, 5, 99); // good mybday.year_=99; // ERROR - private member

  6. Member Function Definitions • member functions can be defined either inside or outside class definition • outside definition (or out-of-line) - class name (called type qualifier) and scope resolution operator (::) precede function name: void Date::set(int month, int day, int year){ month_=month; // no dot with member variables day_=day; // no declaration of member variables year_=year; } • inside definition (or in-line) - replace prototype with definition, no trailing semicolon necessary class Date { public: void set(int, int, int); int getDay(){return day_;} // note no semicolon private: int month_; int day_; int year_; }; // don’t forget semicolon • for style: use for very small functions – one line is good

  7. Mutators and Accessors • accessor function - member function that does not modify the state of an object (only returns the information about the object’s state) • mutator function - member function that modifies the state of an object • accessors should be marked with const type modifier so that compiler can find accidental object state modification • also remember to use const with parameters that are not modified class Date { public: void set(int, int, int); // mutator int getMonth() const; // accessor int getDay() const {return day_;} // accessor in-line private: int month_; int day_; int year_; }; • separate mutators and accessors - a function should not do both • since variables are private, they all need accessor • are we missing an accessor in Date?

  8. Classes with Member Objects • member variables may be basic types or objects of other classes class Meeting{ pubic: void setDate(int, int, int); private: Date d_; Time t_; }; • member objects may be manipulated through pubic methods only void Meeting::setDate(int m, int d, int y){ d_.set(m,d,y); // invokes public member of Date d_.month_ = m; //error, cannot access private members // of Date }

  9. Constructors • function invocation: explicit – if function name is mentioned, implicit - otherwise • constructor – mutator that is invoked implicitly when object is declared • used for object initialization • constructor has the same name as class • constructor does not return a value • do not put void as a return type of constructor class Date{ public: Date(int, int, int); // constructor private: int month_, day_, year_; }; • outside constructor definition (can also be inlined) Date::Date(int month, int day, int year){ month_=month; day_=day; year_=year; } • invocation at declaration: Date mybday(10,26,99);

  10. Multiple/Void Constructors • class can have multiple constructors • which constructor to call is determined by number and type of arguments • function overloading – same name functions distinguished by number/type of arguments • if no constructors declared - object can be defined without initialization • void (or default) constructor - a constructor that does not take arguments • caveat: if at least one constructor declared - object has to be always initialized (needs a void constructor) class Date { public: Date(int, int, int); // constructor Date(int, int); // another constructor Date(); // void or default constructor private: int month_; int day_; int year_; }; • (implicitly) invoking default constructor (if constructors defined): Date mybday; • if array of objects, default constructor is invoked Datefriendsbday[20];

  11. Initializer List constructors can be defined with initializer list: • syntax functionName (parameter list): memberVar(param), … {body (possibly empty)} • example class Date { public: // inline constructor definition with initializer list Date(int month, int day, int year): month_(month), day_(day), year(y_) {} Date(int, int); Date(); private: int month_; int day_; int year_; }; // outside constructor definition with initializer list Date::Date(int month, int day): month_(m), day_(d), year_(2001) {} how would you define the default constructor with initializer list?

  12. Constructors for Member Objects • (void) constructors for member objects are invoked before constructor for containing object • example class One{ public: One() { cout << ”One's constructor" << endl; } }; class Two{ public: Two() { cout << ”Two's constructor" << endl; } private: One o_; }; int main() { Two ob2; } • prints One’s constructorTwo’s constructor • note, if containing object does not have a constructor, member object (void) constructors are still invoked

  13. Initializers for Member Objects • initializer for member object invokes its constructor • example class One{ public: One(int p): p_(p){} private: p_; }; class Two{ public: Two(int o): o_(o) {}; // o_’s constructor invoked private: One o_; // member object }; int main() { Two ob2(5); // object declaration }

  14. Friend Functions • to allow non-member function to access private class members it should be declared as friend function: class Date { public: // compares two dates friend bool equal(const Date&, const Date&); private: int month_; int day_; int year_; }; • a friend-function is not a class member - it’s definition should not be preceded with type qualifier (Date::) • no separate prototype (outside class definition) is necessary for friend • equal is invoked as non-member function – without dot operator: if(equal(date1, date2)) { ... • use friend-function objects are used symmetrically or need to access private members of more than one object • friend-functions circumvent information hiding and should be used with care

  15. Member Constants • constant declared inside the class is only available to class members • good way to limit its scope • can be private or public • static shared between all objects of the class • example class Date { public: ... private: static const int cent21_ = 2001; ... };

  16. Program Layout • program with objects is laid out as follows: • header - class definition (inline function definitions), global constants and other non-executable constructs related to class • program file - member function definitions • multiple related classes may be put in one header/program file pair

  17. Classes Review • What is class? Why are classes needed? • What is object? • What is the difference between object and class? What do we mean when we say object belongs to a class? • What’s member variable? Member function? Method? Attribute? • What’s an in-line/out-of-line function definition? • What are these operators used for? “.” “::” • What is the difference between public and private members of class? • What is the state of an object? • What is mutator? Accessor? How is accessor function distinguished? • What is constructor? Is constructor mutator or accessor? • What is the name of constructor? • What is implicit/explicit function invocation? • How many parameters can constructor take? Can there be more than one constructor? What is constructor overloading? What is void constructor? • What is the return value of constructor? • What is initializer list • What is friend function? Why is it needed? • Why are constants declared inside class definitions? What is static constant?

More Related