Intro the CS 2

do the assignment and read the slides, if you need the book just sign in to account online

Save Time On Research and Writing
Hire a Pro to Write You a 100% Plagiarism-Free Paper.
Get My Paper

Chapter 14:
More About
Classes
Copyright © 2018, 2015, 2012, 2009 Pearson Education, Inc. All rights reserved.
14.1
Instance and Static Members
Copyright © 2018, 2015, 2012, 2009 Pearson Education, Inc. All rights reserved.
Instance and Static Members
instance variable: a member variable in a class.
Each object has its own copy.
static variable: one variable shared among all
objects of a class
static member function: can be used to
access static member variable; can be called
before any objects are defined
Copyright © 2018, 2015, 2012, 2009 Pearson Education, Inc. All rights reserved.
static member variable
Contents of Tree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Tree class
class Tree
{
private:
static int objectCount;
public:
// Constructor
Tree()
{ objectCount++; }
Static member declared here.
// Static member variable.
// Accessor function for objectCount
int getObjectCount() const
{ return objectCount; } Static member defined here.
};
// Definition of the static member variable, written
// outside the class.
int Tree::objectCount = 0;
Copyright © 2018, 2015, 2012, 2009 Pearson Education, Inc. All rights reserved.
Copyright © 2018, 2015, 2012, 2009 Pearson Education, Inc. All rights reserved.
Three Instances of the Tree Class, But Only
One objectCount Variable
Copyright © 2018, 2015, 2012, 2009 Pearson Education, Inc. All rights reserved.
static member function
Declared with static before return type:
static int getObjectCount() const
{ return objectCount; }
Static member functions can only access static member
data
Can be called independent of objects:
int num = Tree::getObjectCount();
Copyright © 2018, 2015, 2012, 2009 Pearson Education, Inc. All rights reserved.
Modified Version of Tree.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Tree class
class Tree
{
private:
static int objectCount;
public:
// Constructor
Tree()
{ objectCount++; }
// Static member variable.
// Accessor function for objectCount
static int getObjectCount() const
{ return objectCount; }
};
// Definition of the static member variable, written
// outside the class.
int Tree::objectCount = 0;
Now we can call the function like this:
cout

Still stressed from student homework?
Get quality assistance from academic writers!

Order your essay today and save 25% with the discount code LAVENDER