0
0
C++programming~10 mins

Data members and member functions in C++ - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Data members and member functions
Create Object
Allocate Data Members
Call Member Function
Access/Modify Data Members
Return or Output Result
End
This flow shows how an object is created with data members, then member functions are called to access or change those data members, and finally results are returned or output.
Execution Sample
C++
class Box {
  int length;
public:
  void setLength(int l) { length = l; }
  int getLength() { return length; }
};
Defines a class Box with a data member length and member functions to set and get its value.
Execution Table
StepActionData Member 'length'Output
1Create object b of class Boxundefined (not set)
2Call b.setLength(10)length = 10
3Call b.getLength()length = 1010
4End of programlength = 10
💡 Program ends after getting length value 10 from object b
Variable Tracker
VariableStartAfter Step 2After Step 3Final
length (data member)undefined101010
Key Moments - 2 Insights
Why is 'length' undefined before calling setLength?
Because data members are not automatically initialized; setLength assigns the value (see execution_table step 2).
How does getLength access the data member?
getLength returns the current value of 'length' stored in the object (see execution_table step 3 output).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'length' after step 1?
Aundefined
B10
C0
DNot declared
💡 Hint
Check the 'Data Member length' column at step 1 in the execution_table.
At which step does 'length' get assigned the value 10?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Data Member length' columns in the execution_table.
If we call getLength() before setLength(), what would be the output?
A10
Bundefined or garbage value
C0
DCompilation error
💡 Hint
Refer to variable_tracker and understand that 'length' is not initialized before setLength is called.
Concept Snapshot
class ClassName {
  data members (variables);
public:
  member functions to access/modify data members;
};
Create object, then use member functions to work with data members.
Full Transcript
This example shows a class named Box with a data member called length. When we create an object b of Box, length is not set yet. We call setLength(10) to assign 10 to length. Then getLength() returns the stored value 10. Data members hold the object's data, and member functions let us safely access or change that data. Without calling setLength first, length would be undefined. This step-by-step trace helps understand how data members and member functions work together in C++.