Objects on C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Objects on C++

How to add objects to a C++ Program

9th Nov 2017, 6:19 AM
Seb TheS
Seb TheS - avatar
1 Answer
+ 21
#include <iostream> // Blueprint(class) class foo { public: // foo's constructor foo(int x) : test(x) { std::cout << "foo has constructed!\n"; } // A simple member function int mul(); // foo's destructor ~foo() { std::cout << "\nfoo has destroyed!\n"; } private: // data member int test; }; // function definition outside the class int foo::mul() { return test * test; } int main() { // An arbitrary integer variable int dummy = 30; // instanciating f1 object out of foo class foo f1(dummy); // print out dummy's value std::cout << "dummy is " << dummy << std::endl; // calling member function using newly instantiated object // and print out its result std::cout << "Square of dummy is " << f1.mul(); } Output: foo has constructed! dummy is 30 Square of dummy is 900 foo has destroyed! [http://cpp.sh/9irfz]
9th Nov 2017, 6:54 AM
Babak
Babak - avatar