C++ scope

Variables store the state of a program. We know that it's the way a program 'remembers' something. This 'state' is also notoriously prone to side-effects. A variable altered in one place can have un-intended consequence in another.

The 'scope' of a variable determines where it can be accessed. A variable with lower scope can be changed with higher confidence (= lower side-effects).

See here for an introduction to scope in C++

C++ also scopes variables in classes. See here for details.

Is the scope of a variable checked at compile-time or run-time?
In other words, can we access a private data member if the class returns a pointer to it?

class PrivacyViolator {
  private:
    char name[256];
  public:
    char* getName() {
      return name;
    }
};

Can I call getName from outside this class and change its contents?
    PrivacyViolator p;
    char* s = p.getName();
    char source[] = "Accessed private variable";
    strcpy_s(s, sizeof(source), source);

Why does the above code work, though it copies a string to an uninitialized variable?

Leave your thoughts below. Then go on to control structures in C++.

Comments

Popular posts from this blog

Relationships in a Relational Database

Data Schema and Blobs

Power On!