Computer Science - Object Oriented Programming Using C++ - Discussion

Discussion Forum : Object Oriented Programming Using C++ - Section 2 (Q.No. 27)
27.
A static data member is given a value
within the class definition
outside the class definition
when the program is executed
never
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
5 comments Page 1 of 1.

Ayesha. said:   5 years ago
C++ static data member.

It is a variable which is declared with the static keyword, it is also known as a class member, thus an only single copy of the variable creates for all objects.

Any changes in the static data member through one member function will reflect in all other object's member functions.

Declaration:

static data_type member_name;

Defining the static data member.

It should be defined outside of the class following this syntax:

data_type class_name :: member_name =value;

If you are calling a static data member within a member function, member function should be declared as static (i.e. a static member function can access the static data members)


Consider the example, here static data member is accessing through the static member function:

#include <iostream>
using namespace std;

class Demo
{
private:
static int X;

public:
static void fun()
{
cout <<"Value of X: " << X << endl;
}
};

//defining
int Demo :: X =10;


int main()
{
Demo X;

X.fun();

return 0;
}

Output

Value of X: 10

Ayesha said:   5 years ago
A const static member variable can be allocated and initialized for the whole class at compile time. They are defined outside the class because they are stored separately rather than as part of objects. Since they are associated with the class and not objects their memory needs to be allocated separately.

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed the in-class definition of entities that needed to be stored in memory as objects.

Static inline function:

A static data member may be declared inline. An inline static data member can be defined in the class definition and may specify an initializer. It does not need an out-of-class definition:.

Struct X
{
Inline static int n = 1;.
};.

Surya said:   7 years ago
A static variable inside a class should be initialized explicitly by the user using the class name and scope resolution operator outside the class.

Rathod said:   1 decade ago
Static data member always defining outside the class definition and declaring inside the class.

Ayesha... said:   5 years ago
Static variables are sometimes called class variables.

Post your comments here:

Your comments will be displayed after verification.