Declaring a simple class, member variables and member functions

Declaring a class means writing its member variables and member functions inside class Name { }; and functions defined outside the class attach to it with the scope resolution operator ::.

9 min read · 9 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

From idea to typed code

You know the theory: a class is a blueprint, an object is the real thing built from it (the Student example from the class-and-object lesson).

Now the canteen till needs its first real component: an Item. Every item has a name and a price, and must print itself on the bill.

Today you write that class, line by line, and learn the two pieces of punctuation that decide whether it compiles: a semicolon and a ::.

Formula

The skeleton the exam wants

class ClassName {

private:

// member variables (the data)

public:

// member functions (the behaviour)

}; <- this semicolon is NOT optional

Member variables + member functions = members. Writing this shell correctly is free marks in any "declare a class" question.

Practical

The Item class, complete and honest

#include <iostream>
#include <cstring>
using namespace std;

class Item {
private:
    char name[30];     // member variable
    double price;      // member variable

public:
    void setData(const char itemName[], double itemPrice) {
        strcpy(name, itemName);   // defined INSIDE the class
        price = itemPrice;
    }
    void display();    // only declared here...
};

// ...and defined OUTSIDE, attached with the scope resolution operator ::
void Item::display() {
    cout << name << "  Rs " << price << endl;
}

int main() {
    Item chai;                  // object created from the class
    chai.setData("Chai", 12.5); // members reached with the dot
    chai.display();             // prints: Chai  Rs 12.5
    return 0;
}

Theory

Why each line is there

  • char name[30]; double price; are member variables: every Item object gets its own copy of these.
  • setData(...) is a member function defined inside the class body (such functions are treated as inline).
  • display(); inside the class is only a declaration, a promise.
  • void Item::display() { } keeps that promise outside. The Item:: prefix (scope resolution operator) tells the compiler this display belongs to Item, not to the free world.

Think first

Trace it in your head

main() creates a second object: Item dosa; dosa.setData("Dosa", 40); dosa.display();

Before tapping: does changing dosa's price disturb chai's price? Why or why not?

Show the answer

No. Each object owns a separate copy of the member variables: chai's name/price and dosa's name/price live in different memory. The member functions exist once and are shared, but they always work on the object that called them (the one before the dot). So dosa.display() prints Dosa Rs 40 while chai remains Chai Rs 12.5.

Quiz

This code fails to compile: class Item { public: void show(); } void show() { cout << "hi"; } Which TWO fixes are needed?

  1. Add a semicolon after the class's closing brace, and define the function as void Item::show()
  2. Remove the public specifier, and rename show to display
  3. Move show() above the class, and add return 0
  4. Only the semicolon is missing; the function definition is fine as written
Show the answer

Add a semicolon after the class's closing brace, and define the function as void Item::show()

Two separate errors: the class body must end with }; (the missing semicolon is the single most common class-declaration error), and the outside definition must be Item::show(), otherwise you have defined an unrelated free function named show while the member stays undefined. Option D tempts everyone: the free function compiles, but the promise made inside the class is never kept.

Watch out

The two punctuation traps

The semicolon after `};`: forgetting it produces confusing errors that point at the NEXT line of your file, not at the class. When a weird error appears right after a class, check the semicolon first.

Bare definitions: void display() {} outside the class is a new free function, not your member. Only void Item::display() {} attaches to the class. Examiners deduct for a missing Item:: even when everything else is right.

Theory

This class is about to grow

Item is deliberately plain. In the coming lessons it gains an enum for its category (snack, meal, drink), then constructors so it initialises itself the moment it is created, and later a place in an inheritance family. Keep this lesson's skeleton in your head: every richer class in this subject is this same shell with more members.

Summary

Key takeaways

  • Declare with class Name { specifiers, members }; and never forget the final semicolon.
  • Member variables hold data; every object gets its own copy of them.
  • Member functions define behaviour: inside the class (inline) or outside with ClassName::.
  • :: is the scope resolution operator: it attaches an outside definition to its class.
  • Create objects with Name obj; and reach members with the dot: obj.function().
  • Memory hook: shell, semicolon, and :: to come home.

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Data Encapsulation and inheritance

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati

Declaring a simple class, member variables and member functions · Object Oriented Programming and Data Structures (OOPs & D.S.) · Gri-Learn