Classes | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Classes

How to call a function from a class in c++

19th Jan 2019, 3:37 PM
Sudhanshu Sharma
Sudhanshu Sharma - avatar
2 ответов
+ 2
#include <iostream> class className { public: void functionName(); }; void className::functionName() { std::cout << "Function called!"; } int main() { className newName; newName.functionName(); return 0; } As you can see above, we create a class of name <className>. In className, we set its public access specifier and have it declare one function <functionName> of void return type. Afterwards, we declare the same function outside of the class, but specify it being of class <className> via className::<function>. We declare its block of code here, being to print "Function called!" After that, we go into the main function and instantiate an object of class <className> in order to be able to call its members. This instance is called <newName>. We then call <newName.functionName()> to access the function from <className> and use its block of code. NOTE: you don't have to always declare the class functions outside of the class itself. That is just something I do.
19th Jan 2019, 5:16 PM
Dread
Dread - avatar
+ 1
https://www.sololearn.com/learn/CPlusPlus/1635/ You can do the same inside the class too!
19th Jan 2019, 4:14 PM
Seniru
Seniru - avatar