Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Static method are use in constructor or not

+9 votes
asked Aug 16, 2024 by Mahendra singh (210 points)

3 Answers

0 votes
answered Aug 17, 2024 by Mohammad Arman (140 points)

Static methods cannot be used by constructors in the same class. This is because static methods belong to the class itself, not to instances of the class. Constructors, on the other hand, are used to initialize instances of the class. When a constructor is called, there is no instance of the class yet, so it cannot access static methods. However, a constructor can call a static method of another class. Additionally, a static method can be used to initialize a static variable in the same class, which can then be used in the constructor.

commented Aug 19, 2024 by Peter Minarik (101,360 points)
Absolutely not.

Static methods belong to the class, not to the instance, thus you can call static methods just fine without the pointer/reference to the instance. See my example above/below.
0 votes
answered Aug 19, 2024 by Peter Minarik (101,360 points)
edited Aug 20, 2024 by Peter Minarik

Yes, you can use static methods in constructors as these static methods do not need a pointer to the object (in construction).

Similarly, static methods can be used to create an instance of the same class (think of a factory method).

You did not specify the language, so I went with C++, but similar logic works in C# and should work in other languages as well. See the example below:

Foo.h

#pragma once

class Foo
{
private:
    int value;

    static void DoSomething();

public:
    static Foo * CreateFoo();
    
    Foo();

    int GetValue();
};

Foo.cpp

#include "Foo.h"

#include <iostream>

void Foo::Initialize()
{
    std::cout << "static void Foo::DoSomething()" << std::endl;
}

Foo * Foo::CreateFoo()
{
    std::cout << "static Foo * Foo::CreateFoo()" << std::endl;
    return new Foo(); // Calling a constructor from a static method
}
    
Foo::Foo()
{
    std::cout << "Foo::Foo()" << std::endl;
    DoSomething(); // Calling a static method from the constructor
    value = 42;
}

int Foo::GetValue()
{
    return value;
}

main.cpp

#include "Foo.h"

#include <iostream>

int main()
{
    Foo * f1 = new Foo();
    std::cout << "Foo's value is: " << f1->GetValue() << std::endl;
    delete f1;

    Foo * f2 = Foo::CreateFoo();
    std::cout << "Foo's value is: " << f2->GetValue() << std::endl;
    delete f2;

    return 0;
}
–1 vote
answered Aug 19, 2024 by swapna (120 points)
static method are not used in constructor
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...