Z
Z
zus2015-10-09 09:43:27
Programming
zus, 2015-10-09 09:43:27

Is it possible to call a function from a C++ class constructor?

Hi all!
The question is, is it possible to call a function from a class constructor? those. without calling a function from main. More or less like this:

// Конструктор Students
Students::Students(std::string name, std::string last_name) 
{                                                                                            
    Students::set_name(name); // Вызываем(создаем) функцию с фактическим параметром
    Students::set_last_name(last_name); // тоже самое. Можно ли так делать?
}

Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2015-10-09
@zus

is it possible to call a function from a class constructor?

Certainly. There are, however, some subtleties with virtual functions.
Students::Students(std::string name, std::string last_name) 
{                                                                                            
    Students::set_name(name); // Вызываем(создаем) функцию с фактическим параметром
    Students::set_last_name(last_name); // тоже самое. Можно ли так делать?
}

The class name (Students::) can be omitted from calls within a class member function.
Fields can be initialized in the constructor's initialization list. For example like this:
class Students
{
...
    std::string name_;
    std::string last_name_;
...
};

Students::Students(const std::string& name, const std::string& last_name): name_(name), last_name_(last_name)
{                                                                                            
}

A
Alexander Taratin, 2015-10-09
@Taraflex

https://ideone.com/D69xjC

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question