Class and Object
Last updated
Was this helpful?
Was this helpful?
// oop_p1_1.cpp
#include <iostream>
using namespace std;
class Book{
public:
string title;
string author;
int numPages;
};
int main(){
Book book1;
book1.title = "Harry Potter";
book1.author = "JK Rowling";
book1.numPages = 1500;
cout << book1.title << endl;
Book book2;
book2.title = "Lord of the Rings";
book2.author = "JRR Tolkien";
book2.numPages = 1300;
cout << book2.title << endl;
return 0;
}// oop_p1_2.cpp
#include <iostream>
using namespace std;
class Book{
public:
string title;
string author;
int numPages;
void display(string title,string author,int numPages){
cout << title << endl;
cout << author << endl;
cout << numPages << endl;
}
};
int main(){
Book book1;
book1.title = "Harry Potter";
book1.author = "JK Rowling";
book1.numPages = 1500;
cout << "object 1" << endl;
book1.display(book1.title,book1.author,book1.numPages);
Book book2;
book2.title = "Lord of the Rings";
book2.author = "JRR Tolkien";
book2.numPages = 1300;
cout << "object 2" << endl;
book2.display(book2.title,book2.author,book2.numPages);
return 0;
};
Harry Potter
Lord of the Ringsobject 1
Harry Potter
JK Rowling
1500
object 2
Lord of the Rings
JRR Tolkien
1300// oop_p1_3.cpp
#include <iostream>
using namespace std;
class Book{
public:
string title;
string author;
int numPages;
};
class people{
public:
string name;
int age;
};
int main(){
Book book1;
book1.title = "Harry Potter";
book1.author = "JK Rowling";
book1.numPages = 1500;
cout << book1.title << endl;
Book book2;
book2.title = "Lord of the Rings";
book2.author = "JRR Tolkien";
book2.numPages = 1300;
cout << book2.title << endl;
people obj1;
obj1.name = "AA" ;
obj1.age = 20;
cout << "My name is " << obj1.name << endl;
cout << "I am " << obj1.age << " years old" << endl;
return 0;
}Harry Potter
Lord of the Rings
My name is AA
I am 20 years old