0

Objects on C++

How to add objects to a C++ Program

9th Nov 2017, 6:19 AM
Seb TheS
Seb TheS - avatar
3 Answers
+ 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