El3ctroGh0st El3ctroGh0st - 1 month ago 13
C++ Question

How can I declare a struct?

I am currently learning C++ and trying to understand the usage of structs.

in C++. As far as I'm aware, if you want to define a function after the main() function, you have to declare it beforehand, like in this function (Please tell me if I'm wrong with it):

#include "stdafx.h"
#include <iostream>
#include <string>

void printText(std::string); // <-- DECLARATION

int main()
{
std::string text = "This text gets printed.";
printText(text);
}

void printText(std::string text)
{
std::cout << text << std::endl;
}


My question now is if there is a way to do the same with structs. I don't want having to always define a struct before the main() function, just because I prefer it like that. However, I get an error when I try doing it like that:

//THIS program DOESN'T work.
#include "stdafx.h"
#include <iostream>
#include <string>

struct Products {std::string}; // <-- MY declaration which DOESN'T work

int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}

struct Products
{
std::string product;
};


When I delete the decleration and instead define the struct before the main function, the program works so I assume I'm somehow wrong with the decleration:

//THIS program DOES work
#include "stdafx.h"
#include <iostream>
#include <string>

struct Products
{
std::string product;
};

int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}


Could someone tell me if there is some way to declare a struct like that? Bear with me if I have any major mistake in the code, I'm just a beginner.
Thanks in advance!

AnT AnT
Answer

You can pre-declare (forward-declare) a class type in C++.

struct Products;

However, a class type declared in this way is incomplete. Incomplete types can only be used in a number of very limited ways. You will be able to declare pointers or references to such type, you will be able to mention it in non-defining function declarations etc., but you will not be able to define objects of such incomplete type or access their members.

If you want to define objects of class Products or access members of class Products, you have no other choice but to fully define the class before such use.

In your case you are defining an object of type Products in main as well as accessing members of class Products there. This means that you have to completely define Products before main.

Comments