Basic Example using Multiple Objects in C++


The code is an example of how to define a class and create objects of that class in C++. The class is named Car and has three public member variables brand, model, and year of type string and int respectively.

In the main() function, two objects carobj1 and carobj2 are created using the Car class. The member variables of these objects are initialized using the dot notation (.) to access the member variables of the object. Then, the member variables of both objects are printed using cout.

Source Code

#include<iostream>
using namespace std;
class Car
{
   public:
    string brand;
    string model;
    int year;
};
int main()
{
  Car carobj1;
  carobj1.brand="BMW";
  carobj1.model="X5";
  carobj1.year=1999;
  Car carobj2;
  carobj2.brand="Audi";
  carobj2.model="A3";
  carobj2.year=1969;
  cout<<carobj1.brand<<" "<<carobj1.model<<" "<<carobj1.year<<"\n";
  cout<<carobj2.brand<<" "<<carobj2.model<<" "<<carobj2.year<<"\n";
  return 0;
}
To download raw file Click Here

Output

BMW X5 1999
Audi A3 1969

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples