I am getting redefinition of class error for the below code. But if I put this definition in a loop there is no error. What is the difference?
using namespace std;
#include <iostream>
using namespace std;
struct MyClass
{
int x;
};
int main()
{
MyClass A;
MyClass A;
return 0;
}
I tried this but still there is same redefinition error:
#include <iostream>
using namespace std;
struct MyClass
{
int x;
};
int main()
{
MyClass* A;
delete(A);
MyClass* A;
delete(A);
return 0;
}
However If I put it in a loop no problem at all:
using namespace std;
struct MyClass
{
int x;
};
int main()
{
for (int i = 0; i < 5; i++) {
MyClass A;
}
return 0;
}
So what is the difference? And how can I delete and redefine a class with the same name. I don't want to find different names. I will use it outside of a loop and push_back those in a vector.
What I want to do is actually:
#include <iostream>
#include <vector>
using namespace std;
struct MyClass
{
int x;
// other variables vectors etc.
};
vector <MyClass> v_A;
int main()
{
MyClass A;
// Use A's methods and give values to its variables and vectors.
v_A.push_back(A);
MyClass A2;
// Use A's DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A2);
MyClass A3;
// Use A's AGAIN DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A3);
// Goes on. I don't want to create different objects A A2 A3 ... A30. I don't want to keep them in the memory.
// I don't want to write 2 3 ... 30
// Is there a way to get rid of them from memory?
return 0;
}
UPDATING THE CODE TO INCLUDE A SOLUTION DEPENDING ON linsock's ANSWER:
#include <iostream>
#include <vector>
using namespace std;
struct MyClass
{
int x;
// other variables vectors etc.
};
vector <MyClass> v_A;
int main()
{
{
MyClass A;
// Use A's methods and give values to its variables and vectors.
v_A.push_back(A);
}
{
MyClass A;
// Use A's DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A);
}
{
MyClass A;
// Use A's AGAIN DIFFERENT methods and give values to its variables and vectors.
v_A.push_back(A);
}
// Goes on. I dont want to create different classes A A2 A3 ... A30. I dont want to keep them in the memory.
// I dont want to write 2 3 ... 30
// Is there a way to get rid of them from memeory?
return 0;
}