Instance Variable - RJAE5/2143-OOP GitHub Wiki

Instance Variables

When a class is instantiated, the object gets a set of attributes from the class definition for itself known as Instance Variables. The object has free reign over this set of variables and they have their own unique spot reserved in memory specifically for this instance. If one particular instance's variables were to change, they would only change for that instance and no other object within the program. This does come with the exception of class variables which are shared amongst all instances.

Example

#include <iostream>

class A
{
    // These are attributes which will become instance variables once instantiated
    int x;
    char y;

public:
    // Default constructor
    A(): x(0), y('A') {} 

    // Setters
    void setx(int i)
    {x = i;}
    void sety(char c)
    {y = c;}

    // Getters
    int getx()
    {return x;}
    char gety()
    {return y;}
};

int main()
{
    // Two instances of type `A` with default values
    A a1; 
    A a2;

    // Changing `a2` instance variables
    a2.setx(2);
    a2.sety('B');

    // Demonstrating different instance variables
    std::cout << "a1's x: " << a1.getx() << std::endl;
    std::cout << "a1's y: " << a1.gety() << std::endl;
    std::cout << "a2's x: " << a2.getx() << std::endl;
    std::cout << "a2's y: " << a2.gety() << std::endl;

    return 0;
}

The code snippet would output a1's instance variables followed by the instance variables of a2:

a1's x: 0
a1's y: A
a2's x: 2
a2's y: B

Important Notes

  • Instance variables are derived from attributes which are declared in the class.
  • Each object has their own set of instance variables in which they manage.

Sources:

  1. https://www.dremendo.com/cpp-programming-tutorial/cpp-instance-variables
⚠️ **GitHub.com Fallback** ⚠️