C++ Program to Illustrate Usage of Structs

This C++ program illustrates the usage of structs. The struct is defined using keyword ‘struct’ followed by its name and then the member declarations, either data-members or functions enclosed in curly braces. The members are set to public by default which is opposite to that of class.

Here is the source code of the C++ program illustrates the usage of structs. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  * C++ Program to illustrate structs
  3.  */
  4. #include <iostream>
  5.  
  6. struct Car {
  7.     std::string brand;
  8.     int age;
  9.     void setAge(void) {
  10.         std::cout << "Enter the age of car : ";
  11.         std::cin >> age;
  12.     }
  13.     void setBrand(void) {
  14.         std::cout << "\nEnter the name of car : ";   
  15.         std::cin >> brand;
  16.     }
  17. };
  18.  
  19. void howOld(Car cc)
  20. {
  21.     if(cc.age > 5)
  22.         std::cout << std::endl << cc.brand << " is very old.";
  23.     else
  24.         std::cout << std::endl << cc.brand << " is very new.";
  25. }
  26.  
  27. int main()
  28. {
  29.     Car cc;
  30.  
  31.     cc.setAge();
  32.     cc.setBrand();
  33.     howOld(cc);
  34. }

$ a.out
Enter the age of car : 10
Enter the name of car : Chevy
Chevy is very old.

Sanfoundry Global Education & Learning Series – 1000 C++ Programs.

advertisement
advertisement
If you wish to look at all C++ Programming examples, go to C++ Programs.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.