0% found this document useful (0 votes)
23 views35 pages

4 2 Static Const

The document discusses static class members in C++, explaining their characteristics, initialization, and accessibility. It covers both static variables and functions, detailing how they can be accessed and their differences from non-static members. Additionally, it includes examples of using objects as function parameters and the 'this' pointer for member function calls.

Uploaded by

gajab3495
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views35 pages

4 2 Static Const

The document discusses static class members in C++, explaining their characteristics, initialization, and accessibility. It covers both static variables and functions, detailing how they can be accessed and their differences from non-static members. Additionally, it includes examples of using objects as function parameters and the 'this' pointer for member function calls.

Uploaded by

gajab3495
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Static, const

object as function parameter (passing


and returning object)
Department of Computer Science & IT,
The University of Lahore
static Class Members
• static class members
– Shared by all objects of a class
– Efficient, when a single copy of data is enough
• Only the static variable has to be updated
– May seems like global variables, but have class scope
• only accessible to objects of same class

– Initialized at file scope


– Exist even if no instances (objects) of the class exist
– Both variables and functions can be static
– Can be public, private or protected
static Class Variables
• Two-Step Procedure:
1. Declare (Inside Class): static int radius;
2. Define (Outside Class): int
Circle::radius=2;

• static Variables
– Default Initialization: 0 or Null (for pointers)
– Initialization: user defined value
– Initialization is made just once, at compile time.
– Accessibility: Private or Public
Public static Class Variables
– Can be accessed using Class name:
cout<<Employee::count;

– Can be accessed via any class’ object:


cout<<e1.count;

– Can be accessed via Non-Static member functions:


cout<<e1.getCount();

– Can be accessed via Static member functions:


cout<<Employee::Stat_getCount();
cout<<e1.Stat_getCount(); //public static
Private static Class Variables
– Cannot be accessed using Class name:
// ERROR  cout<<Employee::count;

– Cannot be accessed via class' object:


// ERROR  cout<<e1.count;

– Can be accessed via Non-Static member functions:


cout<<e1.getCount();

– Can be accessed via Static member functions:


cout<<Employee::Stat_getCount();
cout<<e1.Stat_getCount(); //public static
static Class Functions
• Non-static function:
– Can access: static/non-static data members
and static/non-static methods

• Static functions:
– Can access: static data and static functions
– Cannot access: non-static data, non-static functions,
and this pointer
Public static Class Functions
–Can be invoked using class’s any object:
cout<<e1.getCount();

–Can be invoked using Class name:


cout<<Employee::getCount();
Private static Class Functions
–Cannot be invoked using class’s object
//ERROR  cout<<e1.getCount();

–Cannot be invoked using Class name


//ERROR 
cout<<Employee::getCount();

–Can be invoked within Class:


• Static member functions
• Non-Static member functions
1 // Fig. 7.9: employ1.h
2 // An employee class
3 #ifndef EMPLOY1_H
4 #define EMPLOY1_H
5
6 class Employee {
7 public:
8 Employee( const char*, const char* ); // constructor
9 ~Employee(); // destructor
10 const char *getFirstName() const; // return first name
11 const char *getLastName() const; // return last name
12
13 // static member function
14 static int getCount(); // return # objects instantiated
15
16 private:
static member function and
variable declared.
17 char *firstName;
18 char *lastName;
19
20 // static data member
21 static int count; // number of objects instantiated
22 };
23
24 #endif
25 // Fig. 7.9: employ1.cpp
26 // Member function definitions for class Employee
27 #include <iostream>
28
29 using std::cout;
30 using std::endl; static data member count and
31 function getCount( ) initialized at
32 #include <cstring> file scope (required).
33 #include <cassert>
34 #include "employ1.h"
35
36 // Initialize the static data member
37 int Employee::count = 0;
38
39 // Define the static member function that
40 // returns the number of employee objects instantiated.
41 int Employee::getCount() { return count; } Note the use of
42 assert to test for
43 // Constructor dynamically allocates space for the
memory allocation.
44 // first and last name and uses strcpy to copy
45 // the first and last names into the object
46 Employee::Employee( const char *first, const char *last )
47 {
48 firstName = new char[ strlen( first ) + 1 ];
49 assert( firstName != 0 ); // ensure memory allocated
50 strcpy( firstName, first ); static data member
51 count changed when a
52 lastName = new char[ strlen( last ) + 1 ];
53 assert( lastName != 0 ); // ensure memory allocated
constructor/destructor
54 strcpy( lastName, last ); called.
55
56 ++count; // increment static count of employees
57 cout << "Employee constructor for " << firstName
58 << ' ' << lastName << " called." << endl;
59 }
60
61 // Destructor deallocates dynamically allocated memory
62 Employee::~Employee() static data member count
63 { changed when a
64 cout << "~Employee() called for " << firstName constructor/destructor called.
65 << ' ' << lastName << endl;
66 delete [] firstName; // recapture memory
67 delete [] lastName; // recapture memory Count decremented
68 --count; // decrement static count of employees
because of
69 } destructor calls from
70 delete.
71 // Return first name of employee
72 const char *Employee::getFirstName() const
73 {
74 // Const before return type prevents client from modifying
75 // private data. Client should copy returned string before
76 // destructor deletes storage to prevent undefined pointer.
77 return firstName;
78 }
79
80 // Return last name of employee
81 const char *Employee::getLastName() const
82 {
83 // Const before return type prevents client from modifying
84 // private data. Client should copy returned string before
85 // destructor deletes storage to prevent undefined pointer.
86 return lastName;
87 }
88 // Fig. 7.9: fig07_09.cpp
89 // Driver to test the employee class
90 #include <iostream> If no Employee objects exist
91 count incremented because of getCount must be accessed
92 using std::cout; constructor calls from new. using the class name and (::).
93 using std::endl;
94
95 #include "employ1.h"
96 Number of employees before instantiation is 0
97 int main()
98 {
99 cout << "Number of employees before instantiation is "
100 << Employee::getCount() << endl; // use class name
e2Ptr->getCount() or Employee::getCount() would
101 also work.
102 Employee *e1Ptr = new Employee( "Susan", "Baker" );
103 Employee *e2Ptr = new Employee( "Robert", "Jones" );
104 Number of employees after instantiation is 2
105 cout << "Number of employees after instantiation is "
106 << e1Ptr->getCount();
107 Employee constructor for Susan Baker called.
108 cout << "\n\nEmployee 1: " Employee constructor for Robert Jones called.
109 << e1Ptr->getFirstName()
110 << " " << e1Ptr->getLastName() Employee 1: Susan Baker
111 << "\nEmployee 2: " Employee 2: Robert Jones
112 << e2Ptr->getFirstName()
113 << " " << e2Ptr->getLastName() << "\n\n";
114
115 delete e1Ptr; // recapture memory ~Employee() called for Susan Baker
116 e1Ptr = 0; ~Employee() called for Robert Jones
117 delete e2Ptr; // recapture memory
118 e2Ptr = 0;
119

120 cout << "Number of employees after deletion is "

121 << Employee::getCount() << endl;

122

123 return 0;
count back to zero.
124 }

Number of employees before instantiation is 0


Employee constructor for Susan Baker called.
Employee constructor for Robert Jones called.
Number of employees after instantiation is 2

Employee 1: Susan Baker


Employee 2: Robert Jones

~Employee() called for Susan Baker


~Employee() called for Robert Jones
Number of employees after deletion is 0
const Class Members
• As with member functions, data members can also
be const

• Member Initializer List:


– Can be used to initialize both const and non-const
data members
– consts and references must be initialized using
member initializer
Member Initializer List (Non-const Members)
Member Initializer List (non-static const)
Member Initializer List (References)
Member Initializer List (member object, no default constructor)
Member Initializer List
(parameter name same as data member)
Object as Function Parameter (Passing and returning object)
Object as Function Parameter (Passing and returning object)
1. class Distance{ 1. Distance Distance::add_dist(Distance d2){
2. private:
2. Distance temp;
3. int feet;
3. temp.inches = inches +
4. float inches;
d2.inches; //add the inches
5.
4. if(temp.inches >= 12.0) //if total
6. public:
7. Distance() : feet(0), inches(0.0) { }
exceeds 12.0,
8. 5. { //then decrease inches
9. //constructor (two args) 6. temp.inches -=
10. Distance(int ft, float in) : feet(ft), inches(in) { } 12.0; //by 12.0 and
11. 7. temp.feet++;
12. void getdist() { //increase feet by 1
13. cout << "\nEnter feet: "; cin >> feet; 8. }
14. cout << "Enter inches: "; cin >> inches; 9. temp.feet += feet + d2.feet; //add
15. } the feet
16. 10. return temp; }
17. void showdist() {
18. cout << feet << "\'-" << inches << "\""; }
19.
20. Distance add_dist(Distance); //declaration when there is object returning

21. };
Object as Function Parameter (Passing and returning object)
1. int main(){
2.
3. Distance dist1, dist3; //define two lengths
4. Distance dist2(11, 6.25); //define and initialize dist2
5.
6. dist1.getdist(); //get dist1 from user
7.
8. dist3 = dist1.add_dist(dist2); //dist3 = dist1 + dist2
9.
10. //display all lengths
11. cout << "\ndist1 = "; dist1.showdist();
12. cout << "\ndist2 = "; dist2.showdist();
13. cout << "\ndist3 = "; dist3.showdist();
14. cout << endl;
15. return 0;
16. }
The this Pointer (Extra, Not included in outline/syllabus)
The this Pointer
 this keyword is a special built-in pointer (constant
pointer) that references to the calling object.

 this pointer is passed as a hidden argument to all


non-static member function and is available as a local
variable within the body of all non-static functions.
 Not part of the object itself (this pointer is not
reflected with sizeof(object))

 Can be used to access instance variables within


constructors and member functions
Using the this Pointer
• Examples using this
– For a member function print data member x, either
this->x;
or
(*this).x

• Cascaded member function calls:


– Function returns a reference pointer to the same
object
{ return *this; }
– Other functions can operate on that pointer
Using the this Pointer
• Example of cascaded member function calls:
– Member functions setHour, setMinute, and setSecond all return *this (reference to
an object)

– For object t, consider:


t.setHour(1).setMinute(2).setSecond(3);

– Executes t.setHour(1), returns *this (reference to object) and the expression becomes
t.setMinute(2).setSecond(3);

– Executes t.setMinute(2), returns reference and becomes


t.setSecond(3);

– Executes t.setSecond(3), returns reference and becomes


t; (Has no effect)
1 // Fig. 7.7: fig07_07.cpp
2 // Using the this pointer to refer to object members.
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 class Test {
9 public:
10 Test( int = 0 ); // default constructor
11 void print() const;
12 private:
13 int x;
Printing x directly.
14 };
15
16 Test::Test( int a ) { x = a; } // constructor
17
18 void Test::print() const // ( ) around *this required Print x using the arrow ->
19 { operator off the this pointer.
20 cout << " x = " << x
21 << "\n this->x = " << this->x
22 << "\n(*this).x = " << ( *this ).x << endl;
23 }
24
25 int main()
26 {
27 Test testObject( 12 );
28 Printing x using the dot (.) operator. Parenthesis
29 testObject.print(); required because dot operator has higher
30 precedence than *. Without, interpreted
31 return 0; incorrectly as *(this.x).
32 }
x = 12
this->x = 12
(*this).x = 12

All three methods


have the same result.
1 // Fig. 7.8: time6.h
2 // Cascading member function calls.
3
4 // Declaration of class Time.
5 // Member functions defined in time6.cpp
6 #ifndef TIME6_H
7 #define TIME6_H
8
9 class Time {
10 public:
11 Time( int = 0, int = 0, int = 0 ); // default constructor
12
13 // set functions
14 Time &setTime( int, int, int ); // set hour, minute, second
15 Time &setHour( int ); // set hour
16 Time &setMinute( int ); // set minute
17 Time &setSecond( int ); // set second Noticethe Time & - function
18
returns a reference to a Time
19 // get functions (normally declared const)
20 int getHour() const; // return hour object.
21 int getMinute() const; // return minute Specify object in function definition.
22 int getSecond() const; // return second
23
24 // print functions (normally declared const)
25 void printMilitary() const; // print military time
26 void printStandard() const; // print standard time
27 private:
28 int hour; // 0 - 23
29 int minute; // 0 - 59
30 int second; // 0 - 59
31 };
32
33 #endif
34 // Fig. 7.8: time.cpp
35 // Member function definitions for Time class.
36 #include <iostream>
37
38 using std::cout;
39
40 #include "time6.h"
41
42 // Constructor function to initialize private data.
43 // Calls member function setTime to set variables.
44 // Default values are 0 (see class definition).
45 Time::Time( int hr, int min, int sec )
46 { setTime( hr, min, sec ); }
47
48 // Set the values of hour, minute, and second.
49 Time &Time::setTime( int h, int m, int s )
Returning *this enables
50 { cascading function calls
51 setHour( h );
52 setMinute( m );
53 setSecond( s );
54 return *this; // enables cascading
55 }
56
57 // Set the hour value
58 Time &Time::setHour( int h )
59 {
60 hour = ( h >= 0 && h < 24 ) ? h : 0;
61
62 return *this; // enables cascading
63 }
64
65 // Set the minute value
66 Time &Time::setMinute( int m )
67 {
68 minute = ( m >= 0 && m < 60 ) ? m : 0;
69
70 return *this; // enables cascading
71 }
72
73 // Set the second value
Returning *this enables
74 Time &Time::setSecond( int s )
cascading function calls
75 {
76 second = ( s >= 0 && s < 60 ) ? s : 0;
77
78 return *this; // enables cascading
79 }
80
81 // Get the hour value
82 int Time::getHour() const { return hour; }
83
84 // Get the minute value
85 int Time::getMinute() const { return minute; }
86
87 // Get the second value
88 int Time::getSecond() const { return second; }
89
90 // Display military format time: HH:MM
91 void Time::printMilitary() const
92 {
93 cout << ( hour < 10 ? "0" : "" ) << hour << ":"
94 << ( minute < 10 ? "0" : "" ) << minute;
95 }
96
97 // Display standard format time: HH:MM:SS AM (or PM) printStandard does not
98 void Time::printStandard() const return a reference to an object.
99 {
100 cout << ( ( hour == 0 || hour == 12 ) ? 12 : hour % 12 )
101 << ":" << ( minute < 10 ? "0" : "" ) << minute
102 << ":" << ( second < 10 ? "0" : "" ) << second
103 << ( hour < 12 ? " AM" : " PM" );
104 }
105 // Fig. 7.8: fig07_08.cpp
106 // Cascading member function calls together
107 // with the this pointer
108 #include <iostream> Notice cascading function calls.
109
110 using std::cout;
111 using std::endl;
112
113 #include "time6.h"
114
115 int main()
116 {
117 Time t;
118
119 t.setHour( 18 ).setMinute( 30 ).setSecond( 22 );
120 cout << "Military time: "; Cascading function calls. printStandard must be called
121 t.printMilitary(); after setTime because printStandard does not return
122 cout << "\nStandard time: "; a reference to an object.
123 t.printStandard(); t.printStandard().setTime(); would cause an
124 error.
125 cout << "\n\nNew standard time: ";
126 t.setTime( 20, 20, 20 ).printStandard();
127 cout << endl;

128

129 return 0;

130 }

Military time: 18:30


Standard time: 6:30:22 PM

New standard time: 8:20:20 PM


Quiz#1
Quiz#1
1. Write a program with a class which has one Constant data member
and a constructor to initialize it. Also write main function.

2. Write a program with a class which has one Reference data member
and a constructor to initialize it. Also write main function.

3. Write a program with a class “Distance”, in the class only write data
members , Constructor , a function to add two object and return an
object. (Note: Here main function is optional, write or not it don’t
carry any marks)

You might also like