C++ - How to declare functions within the structure in C++.
IncludeHelp
19 September 2016
In this code snippet/program/example we will learn how to declare and use function within structures in c++ programming language?
In this example we will declare functions within (inside) a structure and then define them outside of the structure.
Function will be accessed in the main() with structure variable.
There will be two function in this program getItem() that will assign values to the structure members (variables) by passing values as arguments and putItem() that will print the values of the structure members (variables).
C++ Code Snippet - Declare and Use of functions within Structure
/*C++ - How to declare functions
within the structure in C++.*/
#include<iostream>
using namespace std;
//structure declaration
struct item_desc{
char *itemName;
int quantity;
float price;
//function to get item details
void getItem(char *name, int qty, float p);
//function to print item details
void putItem();
};
//function definitions
void item_desc::getItem(char *name, int qty, float p){
itemName=name;
quantity=qty;
price=p;
}
void item_desc::putItem(){
cout<<"Item Name: " <<itemName<<endl;
cout<<"Quantity: " <<quantity<<endl;
cout<<"Price: " <<price<<endl;
}
int main(){
//declare structure variable
struct item_desc ITEM;
//get item details
ITEM.getItem("Dove Soap",10,50);
//print item details
ITEM.putItem();
return 0;
}
Item Name: Dove Soap
Quantity: 10
Price: 50