CS1C – Advanced Programming in C++Saddleback College Fall 2011 – J TateyamaClass Constructors & Static Class MembersChapter 4CS1C – Saddleback College Inline Functions In CS 1B we wrote a lot of very small value-returning functions to return an average, the smaller of two numbers etc. These functions typically contained a small expression. There are benefits and drawbacks to defining functions to do small operations. Benefits–Function calls make a program easier to read and understand–Changes to functions are reflected everywhere in a program–Function can be use in any application without rewritingDrawbacks–Calling a function is slower than executing an expression–When a function is called, arguments must be copied, program must branch to a new location, and return address must be copied Overhead associated with function calls can be reduced by using inline functionsCS1C – Saddleback College Inline Function Exampleinline bool Empty(DataPtr head){return head == NULL;} The above declaration requests that the function be expanded "in line" everywhere a call appears in the program. The callif(Empty(head))cout << "Stack is empty";would be expanded during compilation time toif( head == NULL )cout << "Stack is empty";The use of inline is meant to optimize small functions that are called frequently. Note: The inline specification is a request to the compiler. The compiler may choose to ignore this requestCS1C – Saddleback CollegeClass ReviewClass – defines the variables and methods common to objects of a given type. The class provides the blueprint or prototype for the objects. An object is an instance of a class. instance methodsinstance variablesobject (instance of a class)class Rectangle{public: Rectangle( ); Rectangle(float l, float w); float GetLength( ) const; float GetWidth( ) const;private: float recLength; float recWidth;};void main( ) Rectangle recOne;}{CS1C – Saddleback CollegeClass Components ReviewClass Members–data, functions (methods) and type definitions (typedef) –By default all members of a class are private–Member access specifiers must be used to allow access •public•private•protectedMember Functions (methods)–must be declared inside the class–may be defined inside the class (inline)–may be declared as const–when defined outside the class they must use scope resolution•className::methodName(){…}CS1C – Saddleback CollegeClass ConstructorsA member function that is automatically invoked whenever a class object is createdGuarantees the initialization of a class objectMust have the same name as the classNot a void or value returning functionNot invoked using the dot notationMay be overloaded to allow several ways for the data members to be initializedNote: tilde (~classname) is called the destructor and is used to release memoryCS1C – Saddleback CollegeClass Exampleclass Time// Time is in military format{public:Time( ); // default constructorTime(int h, int m, int s); // overloaded constructor with 3 parametersvoid SetTime(int h, int m, int s);void OutputTime() const;void OutputTimeStd() const;void IncrementTime();private:int hour;int minute;int second;};CS1C – Saddleback CollegeInvoking ConstructorsThere are two ways a constructor is invoked. Example – given class TimeImplicit (when object is instantiated)–Time t1, t2(2,35,10), t3;–Object t1 will be set to 0's, t2 will be 2:35:10, and t3 will be set to 0'sExplicit (valid only after object is instantiated)–t1=Time();–t2=Time(2,35,10);–t3=Time(1,30,00);CS1C – Saddleback CollegeConstructor GuidelinesClass should always contain default constructorIf the only constructor you specify requires parameters, and the client fails to send them, the compiler will not create a default constructor for you. This will result in a compilation error.Compiler chooses constructor based on number of arguments and their data typesIf default constructor should not do any initialization then still include it in your implementation file but leave the body empty–Time::Time(){ }Arguments are passed by placing them after the name of the class object being declared–Time time2(10,15,30);CS1C – Saddleback CollegeInitializer ListsConstructors consist of a name, parameter list and body just like functions Initializer lists may also be used to initialize the data members of a class using the class constructorUsed in place of statements in the constructor bodyInitialization then becomes part of the heading for the class constructorProvides means of accessing the constructors for base classes also –More on this when we discuss inheritance next week–This is a very important point to rememberCS1C – Saddleback CollegeInitializer Lists - Example with variablesTime::Time(int h, int m, int s){hour = h;minute = m;second = s;}Can be replaced by Time::Time(int h, int m, int s) : (hour(h),minute(m),second(s)){}Note the proper placement of the “:” and the empty body {}CS1C – Saddleback CollegeInitializer Lists - Example with ConstantsTime::Time(int h, int m, int s){hour = 0;minute = 0;second = 0;}Can be replaced by Time::Time(int h, int m, int s) : (hour(0),minute(0),second(0)){}Note: This constructor can not be used in the same class as the previous constructor since they both have the same signature- returns Time- parameters – 3 intsCS1C – Saddleback CollegeInitializer Lists Example with ValidationTime::Time(int h, int m, int s) : hour ((h >= 0 && h <= 23) ? h : 0), minute ((m>=0 && m <= 59) ? m : 0), second ((s>=0 && s <= 59) ? s : 0){ } Edits the parameter values for h, m, s and if not valid then set to 0.Same as:if (h >= 0 && h <=23) (expression)? hour = h; value if trueelse hour = 0; value if falseCS1C – Saddleback CollegeInitialization ReviewWhen a variable is declared and no initial value is specified, the initial value, if any, depends on the type of the variable and where it is declaredBuilt-In Types:–Variables declared in global scope (outside all blocks) are initialized to their default value–Variables declared inside a function body are not initializedIf an initializer list is not provided for a class member the compiler uses the default constructor for that memberIf the member’s class does not have a default constructor then initialization failsCS1C – Saddleback
View Full Document