C++ Beginner

cpp_019: Basics of Functions, Methods, Static Methods, and Constructors in C++

codeaddict 2025. 4. 5. 19:56

This is a beginner-friendly lesson on four key programming ideas: functions, methods, static methods, and constructors. I’ll use the circle and square analogy to make it visual and simple, explain what an object is first, and compare to Python at the end for those familiar with it. No deep OOP yet — just the basics!

1. Object (First, for Context)

What is an Object?

An object is a specific thing in your program — like a real dog, car, or person. It’s made from a blueprint called a class. In our analogy:

  • Square: The object (a specific thing, like “Buddy the dog”).
  • Class: The design for all squares (e.g., “Dog blueprint”).
  • Example: If “Dog” is the class (blueprint), “Buddy” is an object (a square made from it).
  • Why: Objects let us work with real instances, not just ideas.

2. Function

What is a Function?

A function is a standalone action — a circle floating by itself. It’s not tied to any square (thing). You call it directly to do a task.

  • Picture: A single circle, like a button labeled “Say Hello.”
  • Purpose: Does a job anytime you need it, like printing or calculating.

Example

#include <iostream>

// Function (a lone circle)
void sayHello() {
    std::cout << "Hello!" << std::endl;
}

int main() {
    sayHello(); // Press the circle button => Output: Hello!
    return 0;
}

3. Method

What is a Method?

A method is an action (circle) that belongs inside a specific square (object). It’s something the object can do, and you call it with a dot: square.circle().

  • Picture: A square (the object) with a circle inside labeled “Bark.”
  • Purpose: Lets a specific thing perform its own actions.

Example

#include <iostream>

class Dog { // Blueprint for squares
public:
    std::string name;

    // Method (circle inside the square)
    void bark() {
        std::cout << name << " says Woof!" << std::endl;
    }
};

int main() {
    Dog myDog;        // A square (object)
    myDog.name = "Buddy";
    myDog.bark();     // Press the circle inside myDog => Output: Buddy says Woof!
    return 0;
}

Explanation:

  • myDog is the square (object).
  • bark() is the circle inside it. You call it with myDog.bark() because it’s tied to that square.

Another Example (std::string)

#include <iostream>
#include <string>

int main() {
    std::string name = "Jane"; // A square (string object)
    int len = name.length();   // Circle inside the square => Output: 4
    std::cout << "Length: " << len << std::endl;
    return 0;
}

Explanation: name is a square, and length() is its circle. You call name.length().

4. Static Method

What is a Static Method?

A static method is an action (circle) attached to the class blueprint (the square’s design), not a specific square (object). It works for the whole group, not one instance.

  • Picture: A big square labeled “User Blueprint” with a circle stuck to its edge labeled “Show Count.”
  • Purpose: Does something related to all objects of that type, not one specific object.

Example

#include <iostream>

class User { // Blueprint for squares
public:
    static int count; // Shared by all squares

    // Static method (circle on the blueprint)
    static void showCount() {
        std::cout << "Total users: " << count << std::endl;
    }
};

int User::count = 0; // Set up the shared number

int main() {
    User::count = 2;    // Set total users
    User::showCount();  // Press the circle on the blueprint => Output: Total users: 2
    return 0;
}
  • Explanation:
  • User is the blueprint (big square).
  • showCount() is a circle on the blueprint’s edge. Call it with User::showCount() — no specific square needed.

Method vs. Static Method

  • Method: Inside a square (e.g., user1.speak() — one user speaks).
  • Static Method: On the blueprint (e.g., User::showCount() — counts all users).

5. Constructor

What is a Constructor?

A constructor is a special action (circle) that builds a new square (object) when you create it. It runs automatically to set up the object’s starting stuff.

Example

#include <iostream>

class User { // Blueprint for squares
public:
    std::string name;

    // Constructor (circle that builds the square)
    User(std::string userName) {
        name = userName;
    }

    void speak() { // Method (circle inside the square)
        std::cout << "Hi, I’m " << name << std::endl;
    }
};

int main() {
    User user1("Jane"); // Magic circle builds square user1
    User user2("Sara"); // Magic circle builds square user2
    user1.speak();      // Output: Hi, I’m Jane
    user2.speak();      // Output: Hi, I’m Sara
    return 0;
}
  • Explanation:
  • User(std::string userName) is the constructor circle. It builds user1 and user2 squares with names.

Constructor vs. Function

  • Function: A free circle you call anytime (e.g., sayHello()).
  • Constructor: A circle that builds a square once, when you make it (e.g., User(“Jane”)).

Class vs. Object (Quick Note)

  • Class: The blueprint (big square design) — e.g., User.
  • Object: A specific square made from it — e.g., user1, user2.
  • More Later: In OOP, we’ll dive deeper into this!

Future Topic: Destructor

A destructor is a circle that cleans up a square when it’s done. Preview:

#include <iostream>

class User {
public:
    std::string name;

    User(std::string userName) { // Constructor
        name = userName;
        std::cout << name << " created!" << std::endl;
    }

    ~User() { // Destructor
        std::cout << name << " destroyed!" << std::endl;
    }
};

int main() {
    User user1("Jane"); // Output: Jane created!
    return 0;           // Output: Jane destroyed!
}

Explanation: Automatic Destructor Call

In C++, the destructor (~User()) is a special method that gets called automatically when an object’s lifetime ends. You don’t need to call it yourself with something like ~user1() — C++ handles it for you. Let’s break it down:

  1. Creating the Object:
  • User user1(“Jane”); creates an object called user1.
  • This line triggers the constructor (User(std::string userName)), which sets name = “Jane” and prints “Jane created!”.
  • user1 is now a square (using our analogy) with “Jane” inside it, built by the constructor circle.

2. Object’s Lifetime:

  • user1 is created inside the main() function. In C++, objects like this have a scope — they only live as long as the block of code they’re in (here, the {} of main()).
  • While main() is running, user1 exists and is usable.

3. End of Scope:

  • When return 0; happens, main() finishes, and the program ends.
  • At this point, the scope of main() closes (the } at the end), and any objects created inside it — like user1 — reach the end of their lifetime.

4. Destructor Runs Automatically:

  • C++ automatically calls the destructor (~User()) for user1 when it goes out of scope (i.e., when main() ends).
  • The destructor prints “Jane destroyed!” and cleans up user1 (in this case, just the std::string name is destroyed automatically by its own destructor).

Key Point: You didn’t write ~user1() because you can’t and don’t need to call the destructor manually for objects like this. C++ does it for you when the object’s life is over.

— If you don’t define a destructor, C++ silently provides a default one that automatically cleans up basic member variables (like std::string) when the object’s scope ends.

— When you define a destructor like ~User() { std::cout << name << “ destroyed!” << std::endl; }, it’s just for adding custom actions — like printing a message — since the default cleanup still happens for name; it doesn’t change the memory management here, it only lets you see when the object is destroyed.

Summary with Analogy

  • Function: Lone circle (action) — sayHello().
  • Method: Circle inside a square (object’s action) — myDog.bark().
  • Static Method: Circle on the blueprint (class action) — User::showCount().
  • Constructor: Magic circle building a square — User(“Jane”).