I am trying to create a class object within another class, this enables me to use the object within the main cpp file I want to use without it being enabled globally. However it doesn't seem to work and spits out an error if declared in the classtest.h. However if I initialise it within classtest.cpp it works fine as its within scope. Trying to understand why I cant initialise class object within another class header file. Also I have read that constructor/de constructor is default doest need to be used unless you specifically need to set variables within it.
classtest.cpp
#include <iostream>
#include "classtest.h"
usingnamespace std;
int main()
{
// repclass Test1; << This works if initialised within main() but if removed and use this line in classtest header file it doesnt like it....
Test1.methodFunction();
cout << "The other magic number is : " << Test1.methodFunction2(5,5) << endl;
cout << "The other other magic number is : " << Test1.methodFunction3() << endl;
int a = 10;
int b = 20;
int c = 20;
// 1. Lambada function only specifying referenced integers &a &b into function
auto Lambada1 = [ &a, &b ](int x, int y) { return x + y + a + b; };
cout << "lambada example 1 : " << Lambada1(5, 2) << endl;
// 2. Lambada function allows all references within Scope
auto Lambada2 = [&](int x, int y) { return x + y + a + b + c; };
cout << "lambada example 2 : " << Lambada2(5, 2) << endl;
}
Coder777 - I create the instance in classtest.h - "classtest Test1" - when I try use "Test1.methodfunction()" within the classtest.cpp. I dont want to create instance on main cpp file I want to create the instance on header then use its object components and methods on the main cpp?
tcs - I get the following error -
1 2 3 4 5
root@dev:/home/xxx/class# g++ -std=c++11 classtest.cpp -o classtest.exe
classtest.cpp: In function ‘int main()’:
classtest.cpp:10:4: error: ‘Test1’ was not declared in this scope
Test1.methodFunction();
^
Your given files doesn't seem to generate this error message. Are those files you've given here are really the original ones? F.e. line 1..3 aren't original as well as lines 17 and 11 of "class.h" and "classtest.cpp". You've also named "classtest.h" as class.h. Does there exist both files? So the complier may choose the "classtest.h" while you does offer here "class.h".
Tcs your right it's classtest.h also commented line out on classtest.cpp as showed that it working when initiated on main. Hopefully the above now should error correctly.