0% found this document useful (0 votes)
31 views39 pages

OOPS Manual

Oops

Uploaded by

2021ecpriyankasb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
31 views39 pages

OOPS Manual

Oops

Uploaded by

2021ecpriyankasb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 39
INSTRUCTIONS FOR STUDENTS ‘These are the instructions for the students attending the lab : + Before entering the lab the student should carry the following things (MANDATORY) Identity card issued by the college. Class notes Lab observation book Lab Manual Lab Record vee + Student must sign in and sign out in the register provided when attending the lab session without fail Come to the laboratory in time. Students, who are late more than 10 min., will not be allowed to attend the lab, + Students need to maintain 100% attendance in lab if not a striet action will be taken. Foods, drinks are NOT allowed + All bags must be left at the indicated place. Refer to the lab staff if you need any help in using the lab. Respect the laboratory and its other users. Workspace must be kept clean and tidy after experiment is completed, Read the Manual carefully before coming to the laboratory and be sure about what you are supposed to do. * Do the experiments as per the instructions given in the manual * Copy all the programs to observation which are taught in class before attending the lab session. Lab records need to be submitted before the start of the Lab session (at the calling of attendance preferably) © scanned wth omen scamer Table of Contents List of Programs... 1) Week 1- C+ Basics Hello, World Variables and Input/Output Conditional Statements (if-else) Loops (for and while). ‘Comparison of Two Numbers.. Comparing Ages. Logical AND Operator 2) Week- Display largest Value of 3 numbers... ‘sum of digits of a number . 3) Week-3. Generate Prime Numbers. Largest and Smallest number in a list of numbers Factorial of a number. 4) Week—4. Convert Hours:Mins:Secs to Seconds .. Display Phone number as areacade-Exchange and number Rectangle Class 5) Week = 5 econ Two Friends... Complex Number, 6) Week -6 Single inheritance Multiple Inheritance © scanned wth omen scamer Stack Implementation... Copy constructor. 9) Week — Linked Ui Implementation... Write a C++ Program for binary Search 10) Week - 10. Class Shape() is an abstract class, © scanned wth omen scamer list of Programs Ge] CO Progian rwel col Basic C++ programs Wwk2 | CO! | a) Write a C+ program to read three numbers from the keyboard and display the largest value on the screen, b) Write a C++ program to cheek whether the given number is an Armstrong number or not. (Hint: Armstrong number 153=143 + 5°3 + 343 ). ©) Write a C14 program to find the sum of individual digits of a positive [integer - Wks | COL | a) Write a C++ program to generate all the prime numbers between I and nh, where n is a value supplied by the uset b) Write a C+ program to find both the largest and smallest number in a list of integers, 7 ¢) Write a C+ program to find and display Factorial of a number. [Wk [CO2|/a) Convert time from HH:iMiNESS format to seconds using class in CHF b) A phone number, such as (821) 428-4328. can be thought of as having three parts: the area code 821), the exchange (428) and the number (4328). Write a program that uses a class to store these three parts of a phone number separately, Call the class phone. Create two class objects of type phone. Initialize one, and have the unique number for the other one. Dispiay both the numbers. . ©) Write a program to create a class Rectangle with data members: length, breadth, area and member functions as: -- i) Rectangle & setDimensions(const int&, const int&) sets the length and breadth of arguments using constant references. Use this pointer to return the resized Rectangle by reference. ii) im computeArea() - to compute and returns area of a rectangle. iii) int compute Perimeter() to compute and return perimeter of a rectangle, iv) Two constructors, default constructor to initialize data members to zero and an overloaded constructor as arguments with breadth having a default value. Define all the member functions outside the class. Create objects of Rectangle type Wks Coz arate two classes DM the value of distances. DM stores distance in meters «ind centimetres and DB in feet and inches, Write a program (hat can read values for the elass objects and add one object of DM With another object of DB. Use a friend function 1 carry owt the addition operation. The object that stores the results may be a DM object or DB object, depending on the units in which the results are required. The display should be in the format of feet and inches or meters and centimetres depending on the object on display program ter © scanned wth omen scamer fae | C08 called Complex and implement the following overloading member fanetions that return 9 Complex namber after performing addition of input args. - Function ADDLint a, Complex s) where a is an integer(real part) and s is a complex number. - Funct mnetion ADD(Complex &s, Complex &s2) Create objees of Rectangle ype ‘on heap utilizing both constructors. Use the member functions to modify the rectangle size, compute area, perimeter. Display the area & perimeter of each rectangle a)Writea C + Program that illustrate single inheritance. b)Write a C+ Program that illustrate multiple inheritance, c) Write a C++ Program that illustrate multi-level inheritance. wk7 | CO3 a) Write a C+ program to illustrate the order of execution of constructors and destructors. b) Write a program to invoking derived class member through base class pointer, was | COS Write a program fo ercate a class called STACK using an array of integers. Implement the following operations by overloading the operators “+ and‘ i) S$1=S1 + element; where SI is the object of class STACK and element is an integer to be pushed on the top of stack. ii) int element = $1--; where SI is the object of class STACK. “operator pops the top element. Handle the STACK empty and full conditions and also display the contents after every operation by overloading << operator. wo | COS ‘Write a C+ Program which implements Linked List, with the following operations. Insert in the beginning, Insert at the end, Insert in the Middle. Delete from end, Delete from the start, delete from the middle. Display the Wkio | COS List. Glass Shaped is an abstract class, With members area and perimeter Implement 2 classes Triangle and Rectangle publicly derived from class Shape, wth suitable data members, Implement all the fanetions derived from class shape vn each of the derived classes. Write a C1 ‘program to ereate objects of each of the derived class and assign to the base class (Shape) type pointer/reference Demonstrate runtime polymorphism by calling the Tunetions of the derived class er/reference _| objects by using the base class po CAPSTONE PROJECT (ASSIGNMENT) for 10 marks will be given in MOODLE. ITisan individual task no Group Work. Anybody found copying from another p awarded, Each of you will get Credits/Marks based on ‘the work. erson, both of you will lose marks and zero will be 4 © scanned wth omen scamer This is the simplest C+ + program that prints “Hello, World!" to the console, swstream~ fine! wamespace stl: intmarni) cout << "Hello, World!” <« end return + Demonstrates declaring variables, taking user input, and performing basic arithmetic using namespace std; int main) § int num, num2. out << “Enter two numbers: " n> num >> num int sum = num + num?; cout << "Sum: suin << endl; turn 0. Shows how to use if-else statements to make decisions. include “ostream Using namespace st, int main(y | int number; ee (Eee ene kednuueedse © scanned wth omen scamer "Enter a number: " cont << 7 ein >> number: ir aumber % 2 = 0) { cout << "Even number" << endl; pelse { cout << "Odd number” << endl; return O: } Loops {for and while} «Illustrates for and while loops. gincude using namespace std; int main() { 1) For loop for ( cout < © scanned wth omen scamer sing namespace std, pronation 9 calculate the square of @ number sgt sowaroine nm) turn num * mu; i main() & int numbers cont << "Emter a number cin >> number; jt result = square{number); qoit << "Square: " << result << endl; retum 05 } Arrays 4 Demonstrates the use of arrays. include ‘using namespace std; int main) { int numbers[5] = (1.2, 3.4, 5} cout << "Array elements: "5 for (int = 0; <5; i++) ( cout << numbers[i] <<" "s t cout << endl; return 0; Relational Operators C++ programs that demonstrate t operators: he use of relational operators and boolean Pie cenkaneeceus) @ scanned wh one scomer comparison of Two Numbers + Compates two numbers and prints whether they are equal or not. include “iostream> xing namespace st intmain() { int numa, mum2s cout << "Enter two number cin >> num] >> num2; ir(num) == num?) { cout << "Both numbers are equal." << endl; else { cout << "Numbers are not equal." << endl; return O: } Comparing Ages + Compares the ages of two people and checks if they are eligible to vote ‘#include using namespace stds int main { int agel, age2; coul << "Enter age of person | cin >> agel: cout << "Enter age of person 2: "s cin >> age2; if(agel >= 18 && age2 >= 18) | cout << "Both are eligible to vote." << endl; Jelse { cout <<"At least one person is not eligible to vote." << endl; Moe eeeemseiekcomultats Gri is . © scanned wth omen scamer yeturn 0 goolean Operators: Logical AND Operator ¢ Demonstrates the logical AND operator (88) to check if a number is both positive and even ginclude usiag namespace std; int main() { int num; inter a number cout <<" cin>> num: if(num > 0 && num % 2 == 0) { cout << "The number is positive and even." << endl; j else { cout << "The number does not meet the conditions." << endl; relum 0; el © scanned wth omen scamer week ~ 2 pisplay largest Value of 3 numbers write C+ program to read three numbers from the keyboard and display the largest value on the ser0et sing namespace std; int rain intone. two, three, max: cout << “Enter the frst number: "<< endl; gin >> one: -> two cout <¢ "Enter the first number: " << endl; cin >> three: imax < two) max = two; if (maa © three) three; cout << “Biggest number is " << max << endl; Wate a C++ program to check whether the given number is an Armstrong number or not, (Mint: Armstrong number 153=1/3 4 5°3 «93 ). Hneune siostenm> cmmath> int main() { int.oum, originalNum, remainder, result = 0,0 = Us ‘Input a nurnter from the user namie’ © scanned wth omen scamer aid:cout << “Enler an integer: sudscin >> PUM: criginalNum = nun; yCaleuiate the number of digits a) wile (originalNum criginalNum /= 10: wn coriginalNum = num: {i Check fit is an Armstrong number nM remainder = originalNum % 10; while (originalNum result += pow(remainder, n); originalNum /= 10; sid:cout << num << " is an Armstrong number.” << std:endl, else { std::cout <€ num << " js not an Armstrong number." << std:iendl return 0; Sum of digits of a number Write a C+ program to find the sum of individual digits of a positive integer. Hircovce using namespace std; int sum _of digits(int >) { int digt,sum= while(at=0) © scanned wth omen scamer aigit2n210: eum=sum digit; 10; 1 return sum } int main ( int umber. digits. sum, "Enter Positive integer within the range"; cin>>number cou daits_sum=sum_of digits(number); coulee"sum of digts of" using namespace st void pimerint ( int factors: ccoutesptinie NUMbErS 210, actors=factors+ 1; ) infectors coutedee’ ) int main(){ intr; coutee"Enter a integer values"; cindy prime(n): return 0 Input: Enter a integer value:10 Output: prime numbers are,...1 2357 © scanned wth omen scamer Largest and Smallest number in alist of numbers rite a C+ program to find both the largest and smallest number in a list of integers. fincludesiostream.h> int mainQ) { int a[5O].in.small, large; Enter The Array Siz cout<<' cin>>n source" ENTER ELEMENTS OF ARRAY"; for(i=O;i>ali]: small-a(0]s large=al0]: nsit+) iflali}large) large-alil: } js"< using namespace std; void factoriaint )f int ose; int start = whitest <= 9) ( — —— © scanned wth omen scamer start += 1: cout <> num: factorialinum): reluin 0: } Input Enter the factorial number : 5 Output: 1 2 6 2% 120 Week -4 Convert Hours:Mins:Secs to Seconds Convert time from HH:MMESS format to seconds using class in Cr Conver time irom HH:MIMSSS format to seconds using class in C+ Using namespace std; class Convo public: intcaleSeconds, hrs, mins, Secs; Convert2Seconds{int ".int e,int =} hrs=h; mins =m; sacs = 5; caleSecond: int caleutate() { caleSeconds = caleSeconds + (hrs * 60 * 60) + mins * 60 + secs; ‘elu caleSeconds; eee © scanned wth omen scamer int maind int hs, min, S60, Fes: char colant, colon: “Enter the time in HELMS formal cout <¢ cin 52 colont >> min => colon? >> soc; onver2Seconds timevalue(hrs, min, sec): res = tmovalue.calculate(): put <<"The total seconds in given time is” << res << ond; Anput Enter the time in HH:MM:SS format: 12:13:34 ‘Output The total seconds in given time is : 44014 e number as areacode-Exchange and number ye area code 821), Display Phon! :21) 428-4328, can be thought of as having three parts: th ‘A phone sumber. such as (8 the exchange (428) and the number (4328), Write @ program that uses a class to store these tree pars phone. Initialize of. phone number separately. Call the class phone. Create two class objects of tye cone, and have the unique number for the other one. Display the numbers. tirsiuce ting? lass Prorat amt public: PhoneNumber(const ste: ing& ne if (oumber.size() = 13 |] CH umber(4] I=‘ |) ‘pumber(2] !=~) { std::cout << “Invalid phone number for umber{0] mat, Please use [XXX)KXX-XKXX format.” << std:endl; IsValid_= false: © scanned wth omen scamer yeise areaCode_ = number substi, 3); exchange. = number.subst(S, 2); wumber.substr(®, 4} number. ‘sVale_= tuo) boo isValid() const ( return Valid void oisplayParts(){ it svi.) std:cout <¢ "Area Code: " << areaCode_ << stdendl stdcout <« "Exchange: " << exchange_«« sid:zendl; std::cout << "Number: "<< number << stéziendi: private stdsting ereaCode.; stcsting exchange + stcsving number; bool isValid: int mand { stdstring phoneNumber; stdcout <« "Enter a phone number (in the format (XXX)XXX-XXXX: std:icin >> phoneNumber: + ce phoneNumber.length() << std:endl; std:veout << "Size of the string Is PhoneNumber phene(phoneNumber); if (phone isValid()) { phone.displayParts(); nic © scanned wth omen scamer ) Input inter a phone number (in the format (XXX)XXX-XXXK: (821]400-4956 itu Size of the string is : 13 prea Code: 821 exchange: 400 Number: 4956 rectangle Class rite» program to ereate a class Reetangle with data members: length, brendth, area and member inctions a8: — snide, const int&) sets the length and breadth of ) Rectangle & setDimensions(const i ‘Use this pointer to return the resized Rectangle by arguments using constant references, reference. int computcArea() - to compute and returns area of a rectangle urn perimeter ofa rectangle. tialize data members to zero and an overloaded ii) iii) int compute Perimeter() to compute and re ‘Two constructors, default construeior to init iv) constructor as arguments with breadth having a defaul ik value. Define all the member functions outside the class. Create objeets of Rectangle type and test all the functions. Delete the objects before program terminates File Name: rectangle.h ass Reclonsel private int length; int broach; int area: public: Rectargio & sotDimensionsiconst int’, | const int& 1}; Int computeArea(); int computePerimeter Rectangle(); Rectangletint | int"): File Name: rectangle.cpP CTSA Pee ast ieseins kes ms AcE NEM © scanned wth omen scamer iced iced “ectangle.h using namespace std; Rectangle: Rectangle() { Iength = 05 breadth = 0: rea = 0: Rectangle::Rectangle(int | int b) ( length =; breadth =o; int Rectangle:;computeArea(){ area = length * broach; return area; int Rectangle::computePerimeter.) { int perimeter = 0; + (iength + breadth); perimeter return perimeter; Rectangle & Rectangle::setDimensions( Rectangle recta, by this->length = a; this->breadth return “this; ink maing inten, breadth; cout << “Enter two numbers for lena cn >> len >> breath Rectangle rect, {const int. , const imt& 0) { th and breadth of a rectangle (enter the value giv /e space) © scanned wth omen scamer reel setDimensions(len, breadth): cout << "Area of rectangle is: << rect computearo cout <<"Pormeter of the Rectangle is wane ) Compile command: g++ rectangle.cpp -o rectangle Input ter two num Enter tw¢ bers for length and breadth of a rectangle (enter the value give space): 40 35, "== rect.computePorimoter() << end Output Area of rectangle is: 1400 Perimeter of the Rectangle is: 150 Week- 5 Two Friends Create two classes DM and DB which store the value of distances. DM stores distance in meters and centimetres and DB in feet and inches. Write a program that can read values for the class objects and add one object of DM with another object of DB. Use a friend funetion to carry out the addition operation, The object that stores the results may be a DM object or DB object, depending on the units in which the results are required. The display should be in the format of feet and inches or meters and centimetres depending on the object on display Fincluce 1/ Forward declaration of class OB { private: im meters; int centimeters; public: DM{int 1, int s) : meters(mn), centimeters(em) () 11 Friend function to add DM and DB distances friend Di addDistancos(const L& = 160} { lolalMelers += totalContimeters / 100; totalCentimeters %= 109; return DM(lotaiMeters, totalCentimeters); int maint) ( OM dm(2, So); 412 motors and 50 centimeters 08 db(6, 10); 11 6 foot and 10 inches OM result= addDistances(dm. db): eee © scanned wth omen scamer oitcsnloO: rotun 0: ) complex Number seinen hte a Cons amen ts tevin von 4. Function ADD(int a, ion ADD(Complex &s1, Com, utilizing both constructors, Use the member functions to modify the rectangle size, Display the area & perimeter of each rectangle. Complex s) where a is an integer(real part) and s is a complex iplex &s2) Create objects of Rectangle type on heap. compute area, perimeter. class private double real double imaginary publi: Complex): real(0}, maginary(0) {) Complexidouble «, double ) : real), imaginaryti Ji ember function to add an integer to a Complex number Complex ADDGNt#) ( return Complex(real + a, imaginer): | Member function to add two Gomaiex numbers Comale + ADD(eonst BL reun Complosral+sxca,maginary + Siainay } oid display()( ect" > 11 >> itz std:cout << Enter the fist complex number, ea sidsoin >> 25> ima, Create Comelex objects, Complex ¢1(11, im}; 1 replace with variables ‘Complex c2{r2, im) Add an integer to a Complex number Complex resultt = 1. ADD(2) stdscout << "Resull of ADD{int, Complex): *: result display(); 1 Add two Complex numbers Complex resull2 = 1.ADD(c2): stgcout << "Result of ADD(Complex, Complex)" resul2.display(); return 0; Input ; Enter the first complex number, real followed by imaginary number: 3.02.0 Enter the first complex number, real followed by imaginary number: 2.0 3.0 Output Result of ADD(int, Complex): 5 + 2i Result of ADD(Complex, Complex): 5 + 5i Week- 6 Single Inheritance a)Write a C++ Program that illustrate single inheritance. © scanned wth omen scamer mechanism of deriving & nev ela Feived=HsS-H0e Visibility iy t ‘aing namespace sid ass ‘ protected intab: pubic void get) ( coute<"Entor any two integer values": cin->arob; } class public ° ( ints public: void add) { crate; coutecace"+" ipainclude se sing namespace std; class student { protected: int nom m2; public: void got) { coule<"Enter the Roll no :"; cin>>mo; couls<"Enter the wo marks :*; cin>>mt>>m2; dlass snore { protected: int sm; // sm = Sports mark public: void getsm() { coute<"\nEnter the sports mark"; cin>>sm; public sors dlass statviner public st inttoravg; public void display() ( tore(mtem2esm); avgrtot', ecemno srolude using namespace std; thas op t Public intas void getdata() { coutce"tn\nénter first Number } od putdata() 1 ‘Cout<<"\nFirst Number Is ::\t"<<2 \ oin>>ay ‘ist level inhertance 285 inde spublic top { © scanned wth omen scamer public Wvolass middle is derived_1 int by void square() { gotdata() beeta; coute<"ininSquare Is «"< using namespace std; class Base { public: Base () t coute< “Inside Base constructor" < dass STACK { private int stackarray. int top: int size; publ: STACKints)*top(-"). size) { stackArray = new int[sizel, ~STACKO( delete] stackArray: the stack sy Overload“ operator to push an tere a Ack operatoreint omen fests © scanned wth omen scamer i (FUND) ( Stescout << "Stack isu. Cannot push «yon se dona roturn “this slackArray{+ stop] return “this; Member function to pop an element from the stack int popt){ if (SEmply(y ¢ Std:!cout <= “Stack is emply. Cannot pop." << std:iendl; relum -1;(! Return -1 for empty stack } return stackArrayltop-|; 17 Overload << operator to display the contents of the stack m& operator<<(stdlostream& out, const STACK stack) { friend sté:zost if (ack isEmpty() { oul << "Stack is empty." << stavendl pelse( out << "Stack contents: "; for int i= 0: 1 <= stacs.top: i++) { ul << stack,stackArrayli] <<""; } << stdendl; } return bool isFull() const ( return top == size boo! is mpiy() const ¢ return top Dieu © scanned wth omen scamer int ming) int stackSize = 5; STACK s1(stackSize); 81 + 10:1 Push 10 onto the stack st stdcout << 51; 51°81 + 20:71 Push 20 onto the stack stdzcout << st; int poppedElement = s1,pop(): 17 Pop an element A (poppedEement t= -1){ SEIS“ Popped clement" poppediement << send ) sid:cout<« 81; Push 30 onto the stack sts std:icout << $1; $1 =81 » £2; // Push 40 onto the stack stacout <- 81 $1 ~ 50:11 Push 50 onto the stack stdout << st; 9; 1! Stack is full; cannot push 60 Std::cout © st: return ( struc Write a program using copy constructor to copy tata fiom one ubject wo © siostream> another object, © scanned wth omen scamer ase yD 0 { pnvate intdata: publi Constructor MyObjectlint 94): datatva UGopy cons MyObjectcomsk yO 928 cara f data = other data; void displayDatal) ( sid:enul <* "Data * <« data <« otavenal, int main() { HGrmave an ob MyObject obj1(42); 11 Use the copy consteuctor to create a copy of obit MyObjoc ob = obj; sld:cout << "Object 4. bjt displayDatal), uldcout <* "Object 2 (copy of Objeet 1) je dsplayDatal) return 0; ) Week -9 Linked (iat Implementation . i cis Linked List. with the Following operations Write a Ci + Program which implements 1.10 ch he Fo ore Dele fom the inj, nse id, Insert in the idle. Insert in the begin’ the start, delete from the mm! Ce Ls © scanned wth omen scamer toss Nosh { pbc: int data; Noxdo* next: Noda date), next class Lies private Node* bead; public Linkedtist) : head(nuptr ¥ Insert an element atthe beginning ofthe list, void insertAtBeginningtint sis) { Node" newNode = new Node(vatua} newNode->next = head; head = newNode: Ui tnsert an element al the end ofthe list Mu Node’ newNode = new Node(value), void insentAtEndtint i (head) { head = newNode: return; Node" current = head: While (current->next) { ‘current = current-anext: ) current->next = newNode; area ian ane © scanned wth omen scamer 11 Delete an element by value void dolotoElementtint voy ir ono) return: ) if (head->data == value) ¢ Node temp = heads hhoad = hoad->next delete temp; row; ) Node* cureent = head while (curent->next)( if (curtent->next->data == value) { Node* temp = current>next; current->noxt = temp->next delete temp; return: ) current = current->next: / Diep the Inked fist void display() { Node" current = head: weil (cutent){ std::cout << eurrent->data <<" current = current->noxt } std::cout << “nullp << std:endl; Destructo to free memory ~Linkedtist) { vile (head) { Node" temp = head: head = head->next it FS Cn eselueneeus ele elstela Rance (ee eesasease @ scanned wh one scomer date temp: int mand Linkedist mytist; imyListinsortAtEnd 1): yListinsetAt€nd\2) inybistinsertAtEnd(3); rnyListinsertAt@eginning(0}; stdscout << "Initia List"; myList.cisplay(); myListdoletetlement(2);, stdcout << "After deleting element 2:*; mylistaisplay() return 0; Write a C++ Program for binary Search sy cloe in binarySearchiconst std:vector& av, int targol){ intlen = 0; int right = arr.size() =": wile (left <= right) { int mid = left + (right = left) / 25 if (are) == target) { return mid; i” Element found, return its index else if (arrimid] < target) { left= mid + 1;// Adjust the left boundary else ( 1 adjust te right Bound fight = mi Reise © scanned wth omen scamer ) return 1; Eleriont not found ) fot main) { stdsvoetoreint sortedAmay = (3,3, 5,7 intargot 8.4915, 155 intresul = binarySearch(sontedArray, ta larger); if rosult = 1) std:cout << “Element * << ‘Element * << target << found at index" rir x" << result << sendy stdout << "Element" << target << * not found in the in he array." <« std:enel; To compile binary search program use: Week- 10 Class Shape() is an abstract class. Class Shape() is an abstract class. With members area and perimeter ‘cetangle publicly derived from class Shape, with suitable derived fram class shape in each of the derived f each of the derived class and assign to the intime polymorphism by calling the pointer/reference Implement 2 classes Triangle and Ri data members. Implement all the functions classes, Write a C++program to create objects 0 base class (Shape) type pointer/reference. Demonstrate ru funotions of the derived class objects by using the base class perimeter =a +6 -a-b-cos(7) 4 faty eTocs nee A Toate © scanned wth omen scamer wtual double area) const = 0: vinual double perimeter’) const dass Triangle : public Snape { pv double base: double height outle angle: publi Trianglo(double ©, double », double ~") : baso(b), height(h) ( angle = ang: double arca() const override { return 0.5 * base * height; double perimeter() const override ( sonal information i/Mn a real application, you would need a n(e.g. the lengths of al sides) to caleulate the penmeter. iistd::cout << “Perimeter of a triangle is not implemented" << stc:zendl douse perimeter = base + height + sqt(base"base) + (heightTheight) 2 "base "height cos(engle)k retum perimeter ) class Rectangle : public Shape { private double width: double length ble Rectanglo(double , double): width tengtht Eee ess © scanned wth omen scamer double aroat) const averride ¢ roturn width * Jongth; doublo perimeter() const override ( 2.07 (width + fongth); int main() ( viangle tiangle(4.0, 5, 75); Rectangle rectangle(’.0, 6.0}; Shape* shapePtr; 11 Assign the address of a Triangle object to the base class pointer shapePtr = ▵ sld:cout << "Triangle Area: "<< shapePtr->area() << std-endl; std::cout << "Triangle Perimeter: * << shapePtr->porimeter() << stdendl; I Assign the address of a Rectangle object to the base class pointer shapePlr= rectangle; “ << shapePt->areal) << siéendl; + << shapePtr->porimeter() << sté:zendl std::cout << "Rectangle Area: " std::cout << "Rectangle Perimeter: return 0; ) Compile the shape code with gt (d=ct++L1 shape.cpp -o shape Fee © scanned wth omen scamer

You might also like