Why its important to get a variable to a class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why its important to get a variable to a class?

Hi. to clarify me question I've an example. #include <iostream> using namespace std; class BankAccount { public: void sayHi() { cout << "Hi" << endl; } }; int main() { BankAccount test; test.sayHi(); } in the first line of the main function we recall our class name. I don't undrestant why we need to write "test"! is it an argument for our class? what happend if we wrote like this if we just wanna mention the sayHi BankAccount.sayHi(); thanks.

8th Nov 2016, 9:56 PM
Amin Ghasemi
Amin Ghasemi - avatar
2 Answers
+ 4
that is because 'test' is an object of BankAccount class you can create different object of that class. for instance if you want to store an array of bank accounts for different clients. naturally different bank account have different balances and belong to a different client. so each account belong to a different client, and can have different balances. and about the BankAccount.sayHi(), that is a viable way of calling a method IF and only IF that method is static, and in that case, it should be accesed using the class name. a good example would be to store a static integer in the class which holds a counter, and each time a constructor of that class is called, increment the value. that is a way to keep track of the amount of objects that were created from that class.
8th Nov 2016, 10:05 PM
Burey
Burey - avatar
+ 1
Because each object has an identity you are defining test as identity of BankAccount. Think of test as the name of a variable type BankAccount. If you had a public variable on BackAccount like: public : string owner; You could have: BankAccount test1; test2; test1.owner = "me"; test2.owner = "you";
8th Nov 2016, 10:01 PM
Marco Capo
Marco Capo - avatar